【问题标题】:MongoDB Indexes Based on $in?基于 $in 的 MongoDB 索引?
【发布时间】:2016-02-05 10:05:30
【问题描述】:

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

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"] } 的所有消息的索引)

【问题讨论】:

    标签: mongodb indexing database-design mongodb-indexes database


    【解决方案1】:

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

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

    【讨论】:

    • 你是救生员,谢谢!我一直在为这个问题撞墙有一段时间了......
    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多