Let’s presume I have objects stored in MongoDB with the following structure:
Transaction
{
_id
userId
accountId
}
And assume I have the following index:
db.Transaction.ensureIndex({"userId": 1})
Does the following query take any advantage of the index to minimize search time?
db.Transaction.find( {userId: 'user1234', accountId: 'account1234'} );
That is, does MongoDB use the index to “whittle down” the results by userId and then table-scan for accountId?
db.Transaction.find( {userId: 'user1234', accountId: 'account1234'} ).explain()
{
"cursor" : "BtreeCursor userId_1",
"nscanned" : 2,
"nscannedObjects" : 2,
"n" : 1,
"millis" : 1,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"userId" : [
[
"user1234",
"user1234"
]
]
}
Looking at the explain() for the query says BtreeCursor userId_1, so I presume it got all the users with userId of user1234 and then scanned (the only two items) to find the accountId of account1234 – Is this correct?
Thanks in advance.
Yes, it does.
Yes, you are correct. See here for more information: