MongoDB — Single Field & Compound Indexes
Master Compound Indexes, the Prefix Rule, and the ESR (Equality, Sort, Range) rule for optimal index ordering.
1The ESR Rule for Compound Index Field Ordering
When designing a compound index spanning multiple fields, arrange fields using the ESR Rule:
- E (Equality): Place fields tested for exact match (e.g.
status: "active") FIRST. - S (Sort): Place fields used in
.sort()SECOND. - R (Range): Place fields tested for ranges (e.g.
price: { $gt: 100 }) LAST.
ESR Compound Index Example
// Query: Find products in "electronics", sort by createdAt desc, price > 50
db.products.createIndex({ category: 1, createdAt: -1, price: 1 });
2Understanding Covered Queries
A Covered Query occurs when an index contains all fields requested by a query filter and projection. MongoDB reads results directly from the index in RAM without fetching documents from disk!