Reputation: 633
while using mongodb sort function I noticed that it's examining too many records, but If I didn't use sort it examine only 22 documents and returns them.
I'm trying to get users who bought some products in DESC order.
both products.userIDs
and orderTime
are indexed
db.collection.find({$or:[{'products.userIDs':{$in:usersArray}} , {'item.userIDs':{$in:usersArray}}]})
.sort({orderTime:-1})
.explain();
without sort it docs examined are 22 with sort docs examined are 1602
how can I sort the documents without examine too many documents.
Upvotes: 1
Views: 272
Reputation: 3380
Mongo only uses a single index per query (unless there's an $or
). If you want to have that particular query be well indexed, you'd want to have an index on {"products.userIDS": 1, "orderTime": 1}
. That way, when it finds the documents, they'll already be sorted & it won't need to to do it in memory. The compound index docs have more details.
Upvotes: 2