7. Indexes and Sorting
Sorting can be expensive when MongoDB must collect many candidate documents and sort them in memory or use other supported execution resources. An appropriate index may allow the query to return records in the required order without a separate blocking sort.
Compound sort patterns must align with index ordering or its complete reverse in supported cases. Equality predicates on leading fields can make later index fields useful for sorting.
For example, { status: 1, createdAt: -1 } can support a query that matches one status and sorts by createdAt descending. A sort by unrelated fields may require a separate sort stage.
Use explain output to look for a sort stage and understand the selected plan. Do not assume that creating an index containing the sort field automatically eliminates sorting.
db.orders.createIndex({ status: 1, createdAt: -1 });
db.orders.find({ status: "delivered" })
.sort({ createdAt: -1, _id: -1 })
.limit(25)
.explain("executionStats");- A suitable index can provide the requested order.
- Compound sort patterns must align with index order.
- Equality predicates on leading keys can enable suffix sorting.
- Use explain to verify whether a separate sort is needed.
Does every index containing a sort field eliminate a separate sort stage?