我有一个查询,它查看按优先级标记的日志条目。
db.logs.find({
environment: "production",
priority: {
$in: ["debug", "info"]
}
}).sort({
timestamp: -1
})
此集合现在超过 3GB,这些查询需要 45 秒 才能返回。
像下面这样的查询,仍然会在一秒钟内返回:
db.logs.find({
environment: "production",
priority: "info"
}).sort({
timestamp: -1
})
看来我的索引没有任何帮助。这是我尝试过的:
{ "_id" : 1}
{ "timestamp" : -1}
{ "priority" : 1 , "timestamp" : -1}
{ "environment" : 1 , "timestamp" : -1}
{ "environment" : 1 , "priority" : 1 , "timestamp" : -1}
这些似乎都没有帮助我。有什么方法可以基于分组创建索引吗? (即所有消息的索引 priority: { $in: ["foo", "bar", "bin"] }
)
最佳答案
This excellent blog post解释你的确切情况。本质上,索引是首先独立排序,然后使用您的索引。要使用范围查询 ($in
),您应该以相反的顺序进行索引:{timestamp: -1, priority: 1}
。
也可以使用 .explain
查看您的查询在做什么。对于 scanAndOrder: true
,它必须对集合进行全面扫描并尝试在内存中进行排序,这将花费很长时间。
关于基于 $in 的 MongoDB 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33529867/