B-Tree Indexes & Execution Plan Analysis

B-Tree Indexes & Execution Plan Analysis in NoSQL Databases: Without an index, MongoDB must execute a COLLSCAN (Collection Scan): scanning every single…

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:

  1. E (Equality): Fields checked for exact equality (e.g. status: "active").
  2. S (Sort): Fields used for ordering results (e.g. .sort({ created_at: -1 })).
  3. 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 for IXSCAN (Index Scan). If you see COLLSCAN, an index is missing!
  • totalDocsExamined vs. nReturned: In a perfectly optimized query, totalDocsExamined exactly equals nReturned. If totalDocsExamined is 50,000 and nReturned is 1, the query is scanning unnecessary documents.
  • executionTimeMillis: Time taken on the server.