I created a test MongoDB collection “sampleCollection” with documents which looks like:
"_id" : ObjectId("510929e041cb2179b41ace1c"),
"stringField" : "Random string0",
"longField" : NumberLong(886)
and has index on field “stringField”.
When I execute
db.sampleCollection.find({"stringField":"Random string0"}).explain()
everything is ok:
"cursor" : "BtreeCursor stringField_1",
"isMultiKey" : false,
"n" : 2,
"nscannedObjects" : 2,
"nscanned" : 2,
"nscannedObjectsAllPlans" : 2,
"nscannedAllPlans" : 2,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"stringField" : [
[
"Random string0",
"Random string0"
]
]
}
but
db.sampleCollection.find({$query:{"stringField":"Random string0"}}).explain()
gets me
"cursor" : "BasicCursor",
"isMultiKey" : false,
"n" : 0,
"nscannedObjects" : 4,
"nscanned" : 4,
"nscannedObjectsAllPlans" : 4,
"nscannedAllPlans" : 4,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
}
This is not looks like a problem, but I’m using org.springframework.data.mongodb framework in production and usage of query constructions is an only way to write repositories.
And thus I have a db which completely ignores indexed data.
Is it correct? Or I misunderstood something?
That was funny i cannot decide to say it is a bug or not it is up to you:
There are two available syntax: http://docs.mongodb.org/manual/reference/operator/query/
When you using:
also will
work fine.
When you using your solution (the other syntax):
the output of
Will show like the query not using the index
if you also use .hint for the index it will omit the result. 🙂 (That is i do not really understand)
Fortunately there is another syntax for these operations too: you can use:
it will have the right output and showed for me the usage of the index. Also there is similar syntax for $hint.
You can check the documentation here: http://docs.mongodb.org/manual/reference/meta-query-operators/
I found this really interesting so i turned on the profiler:
i made a test collection (queryTst) with around 250k docs each with only _id and an age field in the structure with an index on age.
For this query:
i got:
for this:
i got:
in the profiler log: for the first
for the second:
which somehow means to me that is the explain() cause the table scan in the mixed syntax.