Without an index, MongoDB must execute a COLLSCAN (Collection Scan): scanning every single document in the collection from beginning to end. With an index, MongoDB traverses an optimized B-Tree in O(log N) time.
1. Index Types & The ESR Rule
A. Compound Indexes
A compound index indexes multiple fields in a specified order:
// Index on category (ascending) and created_at (descending)
db.articles.createIndex({ category: 1, created_at: -1 });
The ESR (Equality, Sort, Range) Rule
When building compound indexes to support complex queries, always order the index fields following the ESR rule:
- E (Equality): Fields checked for exact equality (e.g.
status: "active"). - S (Sort): Fields used for ordering results (e.g.
.sort({ created_at: -1 })). - R (Range): Fields with range filters (e.g.
price: { $gte: 50 }).
// Optimal index for query:
// db.products.find({ status: "active", price: { $gte: 20 } }).sort({ rating: -1 })
// Follow ESR: Equality (status) -> Sort (rating) -> Range (price)
db.products.createIndex({ status: 1, rating: -1, price: 1 });
2. Inspecting Queries with .explain("executionStats")
To verify whether your query uses an index or a slow full collection scan, append .explain("executionStats"):
db.users.find({ email: "alex@codeacademix.dev" }).explain("executionStats");
What to check in the execution output:
stage: Look forIXSCAN(Index Scan). If you seeCOLLSCAN, an index is missing!totalDocsExaminedvs.nReturned: In a perfectly optimized query,totalDocsExaminedexactly equalsnReturned. IftotalDocsExaminedis 50,000 andnReturnedis 1, the query is scanning unnecessary documents.executionTimeMillis: Time taken on the server.