Jeremy Smith
Jeremy Smith

Reputation: 15079

Why isn't this mongo index working?

I am adding the index here:

db.products.ensureIndex({current_features:1})

But then it doesn't appear to have any effect here:

db.products.find({"current_features" : {"$exists" : true}}).explain()
{
    "cursor" : "BasicCursor",
    "nscanned" : 20995,
    "nscannedObjects" : 20995,
    "n" : 2,
    "millis" : 94,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {

    }
}

Upvotes: 0

Views: 192

Answers (1)

Daniel Lemire
Daniel Lemire

Reputation: 3618

You are asking for every tuple which has the specified field, mongo use the index for this since the 2.0 version, from the doc :

Before v2.0, $exists is not able to use an index. Indexes on other fields are still used.

You should use a sparse index instead. A sparse index will basically index only documents that have the indexed field. So your query will be pre-computed which ensures the maximum speed.

Upvotes: 2

Related Questions