2

I have a collection with an index on 'name'.

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

One of my queries is

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

and it uses the index

{
    "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" : "..."
}

I already know from MongoDB regular expression with indexed field that using the BasiCursor will be faster.

> 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" : {

    },
}

How can I tell Mongodb to use the BasicCursor without dropping the index?

Community
  • 1
  • 1
Matteo Suppo
  • 344
  • 1
  • 4
  • 13
  • The [$hint operator](http://docs.mongodb.org/manual/reference/operator/hint/) can be used to force the use of a specific index. Maybe it can also be used to force indices to be ignored by passing an empty object to it? – Philipp Apr 30 '13 at 21:43

1 Answers1

3

You can force the query optimizer to not use any index via hint with $natural:

> db.collection.find({name: {$regex: '^string'}}).hint({ $natural: 1})
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471