基于 $in 的 MongoDB 索引?

标签 mongodb indexing database-design mongodb-indexes database

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

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/

相关文章:

Node.js 服务器无法连接到 MongooseDB

python - 在python中使用cimport有什么优点?

python - 根据存储在另一个列表中的索引替换列表列表中的元素

mysql - 如何在MySQL中为一个联系人存储多封电子邮件,个人邮件等

ms-access - Microsoft Access 2003 是否包含集或多集?

mongodb - bottle-cork 登录后如何加载MongoDB数据库内容 'in place'?

javascript - Express MongoDB find() 基于 _id 字段

mongodb - 从 Java API 取消 MongoDB 查询

ruby-on-rails - rails : How to add add_index to existing table

sql - 大型 PostgreSQL 表 : better to add a column or create a new table to store metadata?