Mastering Database Indexing in MongoDB: Beyond Single-Field Keys
Stop blindly adding indexes. Discover the exact math behind compound index prefix matching, equality-sort-range rules, and memory cache footprint.
The Hidden Price of Index Proliferation
Indexes in MongoDB are not free. While they transform linear table scans (COLLSCAN) into logarithmic B-tree lookups (IXSCAN), every new index imposes a write tax on every insertion, update, and deletion.
When your working set size exceeds RAM capacity, cache thrashing begins, causing latency spikes across the entire database cluster.
The Golden ESR Rule (Equality, Sort, Range)
When designing compound indexes to satisfy complex queries with filtering, sorting, and pagination, follow the ESR rule strictly:
- Equality: Place fields queried with exact equality (e.g.,
status: 'PUBLISHED') first in the compound index definition. - Sort: Place fields required for ordering (e.g.,
publishedAt: -1) second. This allows MongoDB to traverse the index in order without doing an in-memorySORTstage. - Range: Place fields queried with range conditions (e.g.,
views: { $gt: 1000 }) last.
// Correct index according to ESR rule:
// Query: { status: "PUBLISHED", category: techId, publishedAt: { $gte: startDate } }.sort({ views: -1 })
db.posts.createIndex({
status: 1, // Equality
category: 1, // Equality
views: -1, // Sort
publishedAt: -1 // Range
});
Diagnosing Query Plans with Explain Output
Always inspect the execution stats before declaring a query optimized. Look for the ratio between totalDocsExamined and nReturned. In an ideal query, this ratio is exactly 1:1.
Architectural Insights, Delivered Weekly
Join 32,000+ senior engineers, staff architects, and technical founders. No fluff, no sponsored listicles — only deep architectural teardowns.