Arthur Neves
Arthur Neves

Reputation: 12148

MongoDB limit() and sort() Optimization

I am trying to understand why this is happening:

db.items.find({uid: {$in:[34, 54, 53,1,2,3,5,6,7]} }).limit(40).sort({_id:-1}).explain()

returns me:

"cursor" : "BtreeCursor _id_-1_uid_1 multi",
"nscanned" : 167,
"nscannedObjects" : 40,
"n" : 40,
...

However, without the sort

db.items.find({uid: {$in:[34, 54, 53,1,2,3,5,6,7]} }).limit(40).explain()

returns me:

"cursor" : "BtreeCursor uid_1 multi",
"nscanned" : 40,
"nscannedObjects" : 40,
"n" : 40,
...

So what I dont get is, why when I add the sort, it scans more documents? I am sorting by id, also I have this index to try to improve things "_id_-1_uid_1" , but still it scans a lot of documents.

This is a huge issue in my case, because this is my local database, so just a few documents are been scanned, however in my live site, I have millons of documents been scanned for a reason which I dont know what it is.

Can anyone explain me what is going on?

Upvotes: 3

Views: 3659

Answers (1)

EwyynTomato
EwyynTomato

Reputation: 4077

At present (2012/3/14), this is an unresolved bug :

https://jira.mongodb.org/browse/SERVER-3310

Upvotes: 3

Related Questions