3

考虑下面的 Mongo 索引策略和查询,

指数:

db.collec.ensureIndex({a:1,b:1,c:1});

询问:

db.collec.find({"a":"valueA"},{"_id":0,"a":1,"c":1}).sort({"c":-1}).limit(150)

上述查询的解释返回:

/* 0 */
{
    "cursor" : "BtreeCursor a_1_b_1_c_1",
    "isMultiKey" : false,
    "n" : 150,
    "nscannedObjects" : 178,
    "nscanned" : 178,
    "nscannedObjectsAllPlans" : 279,
    "nscannedAllPlans" : 279,
    "scanAndOrder" : true,
    "indexOnly" : true,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 1,
    "indexBounds" : {
        "a" : [ 
            [ 
                "valueA", 
                "valueA"
            ]
        ],
        "b" : [ 
            [ 
                {
                    "$minElement" : 1
                }, 
                {
                    "$maxElement" : 1
                }
            ]
        ],
        "c" : [ 
            [ 
                {
                    "$minElement" : 1
                }, 
                {
                    "$maxElement" : 1
                }
            ]
        ]
    }
}

这里的问题是它清楚地表明查询完全在 Index(as "indexOnly" : true) 上运行。但是为什么"scanAndOrder" : true
根据Btree索引模型,c在索引的尾部,所以可以用来排序。不?

为什么它不被使用?

4

2 回答 2

5

This is correct and also documented.

As to why: The index looks essentially like this tree:

  • A: "value A"
    • B : "ABC"
      • C: 435
      • C: 678
    • B : "BCD"
      • C: 123
      • C: 993

As you can see, the ordering is correct and ascending, but if you'd take the values of c in-order without limiting to a subset of fixed b, you'd get [435, 678, 123, 993], which is not correct, so scanAndOrder is required.

Unfortunately, indexes without index intersectioning are very inflexible.

于 2013-10-22T11:34:52.647 回答
0

如果您使用下面的索引扫描和顺序将是错误的。

db.collec.ensureIndex({a:1,c:-1,b:1});

看一下这个

于 2013-10-22T11:31:29.180 回答