我遇到了一个如何优化这个$match的问题。目前我有以下代码
{ $match: {
$or: [
{ 'card': { $eq: 'card1'},
$and: [
{ 'createdAt': { $gte: three_months }},
{ 'createdAt': { $lte: createdAt }}
]
},
{ 'client': { $eq: 'client1'},
$and: [
{ 'client': { $ne: null }},
{ 'createdAt': { $gte: three_months }},
{ 'createdAt': { $lte: createdAt }}
]
},
{ 'destination_card': { $eq: 'destination_card1'},
$and: [
{ 'createdAt': { $gte: three_months }},
{ 'createdAt': { $lte: createdAt }}
]
},
]
}
{ $limit: 300},
{ $sort: { createdAt: -1 } },但有时计算是错误的,或者它执行的时间太长。请你给出一些如何优化它的想法?首先要感谢大家!
发布于 2020-03-29 08:51:24
如果您使用的是较新版本的MongoDB (我认为是3.6+),查询规划器可以使用多个索引来处理$or。每个分支在createdAt上使用相同的标准,因此您可以将它们收集在一起,只列出一次,例如:
{$match: {
{'createdAt':{$gte: three_months, $lte: createdAt}},
{$or:[
{'card': 'card1'},
{'client': 'client1'},
{'destination_card': 'destination_card1
]}
}}如果创建3个索引,每个索引都有一个精确匹配的字段和createdAt,就像{card:1, createdAt:1}一样,它将改进选择并减少检查的文档数量,这可能有助于提高执行时间。
请注意,使用$or通常会阻止查询执行器使用索引执行排序,每次运行此查询时都需要在内存中进行排序,这会增加执行此查询所需的内存,这可能会在服务器繁忙时减慢执行速度。
https://stackoverflow.com/questions/60901773
复制相似问题