Mastering MongoDB Performance: The Art of Indexing
Is your app slowing down as your data grows? Learn how to use MongoDB indexes to turn 2-second queries into 2-millisecond responses.
Rohit Sharma
Engineering Strategy

Perspective
Practical engineering guidance
Depth
1 focused sections
Use it for
MongoDB indexing guide · database performance tuning
The Cost of a "Collection Scan"
When you query MongoDB without an index, the database has to look at every single document in your collection to find a match. This is called a "Collection Scan" (COLLSCAN). For a collection with 100 documents, it's instant. For a collection with 1,000,000 documents, it becomes an application-killing bottleneck.
What is an Index?
Think of an index like the index at the back of a textbook. Instead of reading the whole book to find "React Native," you look at the index, find the page number, and jump straight there. MongoDB indexes work exactly the same way.
Types of Essential Indexes
- Single Field: The most basic index on a field like
emailorusername. - Compound Index: Indexing multiple fields together (e.g.,
{ category: 1, price: -1 }). This is crucial if you often filter by one field and sort by another. - TTL (Time To Live): Automatically delete documents after a certain time. Perfect for session tokens or temporary logs.
- Text Index: For basic search functionality across your content.
The "Explain()" Command: Your Best Friend
Before you add an index, use .explain("executionStats") on your query. It will tell you exactly how many documents were examined and how long it took. If you see totalDocsExamined is 1,000,000 but nReturned is only 5, you have a major indexing problem.
The Trade-off: Write Performance
Indexes aren't free. Every time you insert or update a document, MongoDB has to update all related indexes. If you have "Index Overload" (30+ indexes on one collection), your write operations will slow down significantly. Only index fields that are used frequently in your find or sort operations.
Monitoring with MongoDB Atlas
If you use Atlas, the "Performance Advisor" will literally tell you which queries are slow and suggest the exact index you need to fix them. It's like having a senior DBA helping you 24/7.
Conclusion
Optimizing your database is one of the highest-leverage things a developer can do. A few well-placed indexes can save you hundreds on server costs and provide a vastly better experience for your users.
