如何强制mongodb使用BasicCursor而不是索引

时间:2013-04-30 21:32:44

标签: mongodb

我有一个带有'name'索引的集合。

> db.search.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_"
    },
    {
        "v" : 1,
        "key" : {
            "name" : 1
        },
        "name" : "name_1"
    }
]
> 

我的一个疑问是

> db.collection.find({name: {$regex: '^string'}}).explain()

并使用索引

{
    "cursor" : "BtreeCursor name_1 multi",
    "isMultiKey" : false,
    "n" : 25,
    "nscannedObjects" : 25,
    "nscanned" : 3247,
    "nscannedObjectsAllPlans" : 25,
    "nscannedAllPlans" : 3247,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 366,
    "indexBounds" : {
        "name" : [
            [
                "",
                {

                }
            ],
            [
                /string/,
                /string/
            ]
        ]
    },
    "server" : "..."
}

我已经从MongoDB regular expression with indexed field知道使用BasiCursor会更快。

> db.search.find({name: {$regex: 'string'}}).explain()
{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 27,
    "nscannedObjects" : 3385,
    "nscanned" : 3385,
    "nscannedObjectsAllPlans" : 3385,
    "nscannedAllPlans" : 3385,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 20,
    "indexBounds" : {

    },
}

如何告诉Mongodb在不删除索引的情况下使用BasicCursor?

1 个答案:

答案 0 :(得分:3)

您可以强制查询优化器不使用hint $natural的任何索引:

> db.collection.find({name: {$regex: '^string'}}).hint({ $natural: 1})