MongoDB-将$ ne和$ in与复合多键索引一起使用时不使用索引

问题描述:

        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数组中指定的值.如果它包含现有文档的所有值,则不使用索引.

use the index. Hitting the index seem to be dependent on the values specified in the $in array. If it contains all the values of an existing document then the index is not used.

Mongo版本-2.4.6

Mongo version - 2.4.6

谢谢.

In the docs, it states that:

$ ne $ nin 运算符不是选择性的.请参阅创建确保选择性的查询.如果您需要使用这些,那就是通常最好确保附加的,更具选择性的标准是查询的一部分.

The $ne and $nin operators are not selective. See Create Queries that Ensure Selectivity. If you need to use these, it is often best to make sure that an additional, more selective criterion is part of the query.