What happens when you query two fields, given that they’re not part of a compound index, for example:
db.collection.ensureIndex( { a: 1 } )
db.collection.ensureIndex( { b: 1 } )
db.collection.find( { a: 2, b: 2 } )
I’d like to know if a number of documents might be scanned, or if Mongo DB won’t scan anything and the explain() will return:
indexOnly: YES
The explain only returns
indexOnlyif all the values you are looking for are in index (including the sort). Basically it denotes a covered index: http://docs.mongodb.org/manual/applications/indexes/#create-indexes-that-support-covered-queriesIn this case you are querying by two fields but only one of them is in one individual index.
Considering MongoDB cannot use multiple indexes for a single clause (
$orbeing the exception since it is multi-clause here also it is different than a normal query) it will not do anindexOnlyquery, instead it will search the collection by the index onaand then do a full document scan of the documents that containbwithin that range to understand its values and return a result.Do also note that to use
indexOnlycursors properly you should make the following parts of the your query fit into a single index:i.e.:
Would use a
indexOnlycursor.