In the early stages of building an application with MongoDB, everything feels effortlessly fast. Documents insert with millisecond latency, simple queries return almost instantaneously, and flexible schemas allow rapid prototyping. But as your collections scale from ten thousand documents to millions, performance can suddenly hit a wall.
Unindexed queries force MongoDB to perform a Collection Scan (COLLSCAN), reading every single document from disk into memory. CPU usage spikes to 100%, query response times degrade from 5ms to 12,000ms, and your application’s database connection pool becomes saturated.
Proper indexing is the single highest-impact optimization you can make for MongoDB. In this guide, we will explore the internal mechanics of B-tree indexes in MongoDB, how to use the ESR (Equality, Sort, Range) rule to design high-throughput compound indexes, and how to analyze query execution plans with explain("executionStats").
Table of Contents
- 1. How MongoDB Indexes Work Under the Hood
- 2. Diagnosing Slow Queries with explain()
- 3. The Golden Rule of Compound Indexes: ESR
- 4. Specialized Indexes: Partial, TTL, and Text
- 5. Optimizing Aggregation Pipelines ($match, $sort, $project)
- 6. 4 Indexing Anti-Patterns That Hurt Performance
- 7. Frequently Asked Questions (FAQ)
1. How MongoDB Indexes Work Under the Hood
By default, MongoDB creates a unique index on the _id field of every collection. When querying any other field without an index, the database engine must inspect every document sequentially (a COLLSCAN).
MongoDB indexes are structured as B-Trees. An index holds a sorted subset of fields pointing directly to the disk locations of full documents. When you query an indexed field, MongoDB performs an IXSCAN (Index Scan) in logarithmic time O(log N) instead of linear time O(N).
2. Diagnosing Slow Queries with explain()
Before creating an index, never guess what MongoDB is doing. Always inspect the execution plan using executionStats:
// Run in mongosh or MongoDB Compass
db.orders.explain("executionStats").find({
status: "COMPLETED",
createdAt: { $gte: new ISODate("2026-01-01") }
}).sort({ totalAmount: -1 });
When analyzing the output JSON, look for these three critical metrics:
stage: If you seeCOLLSCAN, an index is missing. If you seeIXSCANfollowed byFETCH, the index was used.totalDocsExamined: How many full documents MongoDB had to read from disk.nReturned: How many documents actually matched the query.
The Golden Ratio: In a well-optimized query, totalDocsExamined / nReturned should be as close to 1.0 as possible. If your database examined 500,000 documents to return 10 results, your index strategy needs immediate attention.
3. The Golden Rule of Compound Indexes: ESR
When querying on multiple fields with filtering and sorting, creating multiple single-field indexes is inefficient. You need a Compound Index. The order of keys in a compound index is paramount, governed by the ESR Rule:
- Equality (E): Place fields matched with exact equality (e.g.
status: "ACTIVE",userId: 104) first. - Sort (S): Place fields used in the
.sort()clause second. This prevents MongoDB from loading un-sorted records into RAM for an expensive in-memory sort. - Range (R): Place fields using comparison operators (
$gt,$lt,$in) last.
// Query: Find completed orders for user 42, sorted by amount, within date range
db.orders.find({
userId: 42, // Equality
createdAt: { $gte: startDate } // Range
}).sort({ totalAmount: -1 }); // Sort
// PERFECT Compound Index according to ESR:
db.orders.createIndex({
userId: 1, // 1. Equality
totalAmount: -1, // 2. Sort
createdAt: 1 // 3. Range
});
4. Specialized Indexes: Partial, TTL, and Text
MongoDB provides several specialized index types that save significant RAM:
- Partial Indexes: Only index documents that match a specific filter expression. For example, if you only query active users:
db.users.createIndex(
{ email: 1 },
{ partialFilterExpression: { status: "ACTIVE" } }
);This cuts index size by 80% if most users are archived or inactive.
- TTL (Time-To-Live) Indexes: Automatically delete temporary documents (like user sessions or password reset tokens) after a specified duration:
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 86400 } // Deletes automatically after 24 hours
);
5. Optimizing Aggregation Pipelines ($match, $sort, $project)
In complex aggregation pipelines, indexes can only be utilized by the stages at the very beginning of the pipeline:
- Always put
$matchat the very first stage of your pipeline to reduce the dataset as early as possible. - If using
$sort, place it immediately after$matchso MongoDB can leverage a compound index for the sort stage. - Avoid putting
$projector$unwindbefore$matchor$sort, as this breaks index usage.
6. 4 Indexing Anti-Patterns That Hurt Performance
- Over-Indexing: Every index consumes RAM and adds write overhead. On every
insertordelete, MongoDB must update every B-tree index in addition to writing the document. Keep indexes focused on frequent query paths. - Index Not Fitting in RAM: MongoDB performs best when the working set (data + indexes) fits into RAM. Check index size with
db.collection.stats().totalIndexSize. - Redundant Indexes: If you have an index on
{ a: 1, b: 1 }, you do not need a separate index on{ a: 1 }because the compound index automatically covers queries on prefixa. - In-Memory Sort Spill: If MongoDB cannot use an index for sorting and the sorted dataset exceeds 100 MB (or 32 MB in older versions), the query will abort with an out-of-memory error unless
allowDiskUseis enabled.
7. Frequently Asked Questions (FAQ)
What is a Covered Query in MongoDB?
A covered query is a query where all matched fields and all projected return fields are completely present inside the index itself. MongoDB does not need to fetch the document from disk at all (stage: PROJECTION_COVERED), providing the fastest possible response time.
Can MongoDB use multiple indexes for a single query?
Yes, through Index Intersection (AND_SORTED stage), but it is usually much slower than a single well-designed compound index. Compound indexes should always be preferred over relying on index intersection.
How do I identify unused indexes in production?
Run db.collection.aggregate([{ $indexStats: {} }]). Inspect the accesses.ops field for each index. Any index with 0 operations after weeks of production traffic is dead weight and should be safely dropped.
Published by Mohit Kumar — Software Engineer and Founder of Tech Aventure. For deeper backend architecture discussions, explore our guide on containerizing production applications with Docker.
Related Architectural Deep Dives
Continue expanding your technical depth with our related engineering guides:
- Related Resource: Deep dive into our guide on History of MongoDB: Key Milestones Explained.
- MongoDB Indexing Strategies & Slow Pipelines: Optimizing slow aggregation pipelines using compound indexes and explain plans. Explore the complete guide: MongoDB Indexing Strategies & Slow Pipelines.
- MongoDB Sharding & Replication Architecture: Designing fault-tolerant distributed MongoDB clusters with zero downtime. Explore the complete guide: MongoDB Sharding & Replication Architecture.
Related Modular Guides & Next Steps
- CAP Theorem & Partitioning: Explore Database System Design Fundamentals: ACID, CAP Theorem, and Distributed Consistency Models.
Authoritative Reference: Consult the MongoDB Official Indexing Documentation for normative standards and release specifications.




