Rthp
Rthp

Reputation: 85

mongodb query not using index

I have a index:

{
    "sourceName" : 1,
    "addedDate" : 1,
    "sourceKey" : 1,
    "appKey" : 1,
}

But when I try to do

db.myCollection.find({and:[
               {sourceName: "mySourceName"},
               {addedDate: 1414878162405},
               {sourceKey:"mySource Key"},
               {appKey: "test"}]
               }).explain()

It shows cursor is BasicCursor i.e it is not using the index:

{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 0,
    "nscannedObjects" : 500,
    "nscanned" : 500,
    "nscannedObjectsAllPlans" : 500,
    "nscannedAllPlans" : 500,
    "scanAndOrder" : false,
    "indexOnly" : false,
    ...
}

Can anyone please explain me why my query is not using defined index??

Upvotes: 1

Views: 470

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311845

Your query object uses and instead of the $and operator so it's looking for an field named 'and' in your documents that contains your query values.

But you don't need to be using $and anyway, as multiple query terms are implicitly ANDed so you can just do:

db.myCollection.find({
       sourceName: "mySourceName",
       addedDate: 1414878162405,
       sourceKey:"mySource Key",
       appKey: "test"}
   }).explain()

That should be able to use your index just fine.

Upvotes: 2

Related Questions