【问题标题】:MongoDB - Index not used when using a $ne and a $in with a compount multikey indexMongoDB - 将 $ne 和 $in 与复合多键索引一起使用时不使用索引
【发布时间】:2015-04-22 20:55:38
【问题描述】:
        db.test.find().pretty();
    {
        "_id" : ObjectId("5537f2cfba0bf10870747d7e"),
        "a" : 1,
        "b" : [
            "abcd",
            "xyz"
        ]
    }


    db.test.getIndexes();
    [
        {
            "v" : 1,
            "key" : {
                "_id" : 1
            },
            "ns" : "test.test",
            "name" : "_id_"
        },
        {
            "v" : 1,
            "key" : {
                "a" : 1,
                "b" : 1
            },
            "ns" : "test.test",
            "name" : "a_1_b_1"
        }
    ]

db.test.find({a: { $ne : 2}, b : { $in : ["abcd", "xyz"]}}).explain();
{
    **"cursor" : "BasicCursor", - doesn't hits index**.
    "isMultiKey" : false,
    "n" : 1,
    "nscannedObjects" : 1,
    "nscanned" : 1,
    "nscannedObjectsAllPlans" : 3,
    "nscannedAllPlans" : 3,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "indexBounds" : {

    },
    "server" : "vishals-Mac-mini.local:27017"
}

其他查询,

db.test.find({a: 1, b : { $in : ["abcd", "xyza"]}}) 
db.test.find({a: { $ne : 2}, b : { $in : ["abcd", "xyza"]}})

使用索引。 命中索引似乎取决于 $in 数组中指定的值。如果它包含现有文档的所有值,则不使用索引。

Mongo 版本 - 2.4.6

谢谢。

【问题讨论】:

  • 您使用的是哪个版本的 MongoDB? 2.6 对您发布的每个查询都按预期使用索引。

标签: mongodb indexing


【解决方案1】:

docs中声明:

$ne$nin 运算符没有选择性。 See Create Queries that Ensure Selectivity。如果你需要使用这些,那就是 通常最好确保一个额外的、更具选择性的标准 是查询的一部分。

【讨论】:

  • 感谢您的回复。我知道 $ne 不是选择性的,我希望它会进行完整的索引扫描,但至少它应该至少命中索引而不是诉诸基本光标。更令人困惑的是,$ne 确实根据 $in 子句中的值命中了某些查询的索引。
猜你喜欢
  • 2021-09-04
  • 2016-10-19
  • 2015-08-08
  • 2012-03-24
  • 2018-04-16
  • 2012-06-05
  • 2012-11-16
  • 2016-05-04
  • 1970-01-01
相关资源
最近更新 更多