Bikas Katwal
Bikas Katwal

Reputation: 2035

MongoDB sort performance when used with $in query

I have a collection product in my DB. Below is one sample document:

{
"sku_id":"12345678",
"priduct_name":"milk",
"product_rank":3,
"product_price": 2.4
}

There are 100k such unique documents in our collection. I want to query this collection using $in query, as shown below.

db.product.find({"sku_id" :{$in :["12345678","23213"]}}).sort( { product_rank: 1 } )

Our requirement is to search documents based on $in query and sort any field in document(asc or desc). I have created both forward and reverse index on all fields for this collection.

Note: This sku_id array inside $in query can have 1000+ sku_ids.

My doubt is if I use the filter like $in with an array of sku_id and get the sorted result on any field, will it use the index for sorting or will it sort at query time?

Upvotes: 0

Views: 246

Answers (1)

Rakshith Murukannappa
Rakshith Murukannappa

Reputation: 589

Mongo allows you to find out if a query will use an index. As the find operation returns a cursor you can extend the method chain to include an explain() command which does exactly what you need. (suggest you use db.product.find(...).sort(...).explain('executionStats'))

Will it use the index for sorting or will it sort at query time?

The index created on the product_rank will be used in the query but, not an index on the sku_id alone. Instead create a compound index with both product_rank and sku_id(asc and desc).

Upvotes: 1

Related Questions