MongoDB:$match with$or聚合优化



我遇到了一个如何优化这个$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 } },

但有时计算错误或执行时间过长。请你能给出一些如何以某种方式优化它的想法吗?非常感谢!

如果您使用的是更新版本的MongoDB(我认为是3.6+(,那么查询规划器可以使用多个索引来处理$or。每个分支在createdAt上使用相同的标准,因此您可以将其收集在一起,只列出一次,例如:

{$match: {
{'createdAt':{$gte: three_months, $lte: createdAt}},
{$or:[
{'card': 'card1'},
{'client': 'client1'},
{'destination_card': 'destination_card1
]}
}}

如果创建3个索引,每个索引都有一个完全匹配的字段,并像{card:1, createdAt:1}一样创建dAt,它将改进选择并减少检查的文档数量,这可能有助于执行时间。

请注意,使用$or通常会阻止查询执行器使用索引执行排序,每次运行此查询时都需要在内存中进行排序,这会增加执行此查询所需的RAM,这可能会在服务器繁忙时减慢执行速度。

最新更新