我有一个包含具有这种格式的文档的集合(我将它们简化为将字段仅缩小为我要过滤的字段):
{
"payload" : {
"asset" : "1234567890",
"recorded_at" : "2018-10-11T04:51:48Z",
"fields" : {
"ignition": "A54"
}
}
}
我经常要做的是搜索所有具有以下内容的文档:
recorded_at
我定义了以下索引:
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "db_name.md_event"
},
{
"v" : 2,
"key" : {
"payload.fields.ignition" : 1
},
"name" : "payload.fields.ignition_1",
"ns" : "db_name.md_event"
},
{
"v" : 2,
"key" : {
"payload.asset" : 1
},
"name" : "payload.asset_1",
"ns" : "db_name.md_event"
},
{
"v" : 2,
"key" : {
"payload.recorded_at" : -1
},
"name" : "payload.recorded_at_-1",
"ns" : "db_name.md_event"
}
]
现在让我们说以下查询:
db.md_event.find({"payload.recorded_at":{"$gte":"2018-10-02T00:00:07Z","$lte":"2018-10-02T04:52:25Z"},"payload.asset":"355565072950945"})
我首先要理解的是,为什么数据库首先使用recorded_at
索引,然后第二位使用asset
字段(我认为是这样做的,因为db.md_event.find({"payload.asset": "355565072950945"}).count()
返回{{1 }},而225707
返回db.md_event.find({"payload.recorded_at":{"$gte":"2018-10-02T00:00:07Z","$lte":"2018-10-02T04:52:25Z"}}).count()
)
还可以优化我使用的索引吗?这些查询最多可能需要10秒钟才能运行,我希望尽可能减少查询时间。
这是973001
的结果:
explain