MongoDB - 在使用$ ne和$ in并使用compount多键索引时未使用索引

时间:2015-04-22 20:55:38

标签: mongodb indexing

        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

感谢。

1 个答案:

答案 0 :(得分:0)

docs 中,它声明:

  

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