MongoDB 基于 $in 的索引?

MongoDB Indexes Based on $in?

我有一个查询,它查看按优先级标记的日志条目。

db.logs.find({
    environment: "production",
    priority: {
        $in: ["debug", "info"]
    }
}).sort({
    timestamp: -1
})

此集合现已超过 3GB,这些查询花费的时间超过 45 秒 至 return。

像下面这样的查询,仍然 return 一秒钟:

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}

None 这些似乎对我有帮助。有什么方法可以基于分组创建索引吗? (即 priority: { $in: ["foo", "bar", "bin"] } 中所有消息的索引)

This excellent blog post 解释了您的具体情况。本质上,索引是 first 独立排序,然后使用您的索引。要使用范围查询 ($in),您应该以相反的顺序进行索引:{timestamp: -1, priority: 1}.

也可以使用 .explain 查看您的查询在做什么。使用 scanAndOrder: true 它必须对集合进行全面扫描并尝试在内存中进行排序,这将花费很长时间。