When your MongoDB queries slow down, it’s often because you’re missing the right index. And it’s one of the common MongoDB query mistakes.
An index in MongoDB is like the index of a book: it helps you jump directly to the data you need instead of flipping through every page.
Without indexes, MongoDB performs a collection scan, checking every document. With indexes, it goes straight to matching values.
🔍 A Simple Query Example:
db.users.find({ name: "Alice" })
✅ With an index on { name: 1 }, this is lightning fast.
🚫 Without it, MongoDB scans every document.
Time saved? In our test:
- Without index: ~430ms
- With index: ~3ms
What Fields Should You Index?
Example 1 — Filtering on multiple fields
db.orders.find({ status: "shipped", userId: ObjectId("...") })
✅ Ideal index:
db.orders.createIndex({ status: 1, userId: 1 })
This helps MongoDB quickly locate documents where both status and userId match.
Example 2 — Sorting + filtering
db.products.find({ category: "Books" }).sort({ price: -1 })
✅ Recommended index:
db.products.createIndex({ category: 1, price: -1 })
Why? The sort and filter use the same index, saving time and RAM. Checkout out our $sort performance optimization post.
Example 3 — Unique constraint
db.users.createIndex({ email: 1 }, { unique: true })
Useful for ensuring no duplicate emails — data integrity enforced by the DB.
🧪 Try Indexes Safely in Mongo Pilot
Mongo Pilot lets you:
- ✅ Run your query
- 📊 See query stats and performance with and without an index experiment
- Apply or remove the index experiment
Benchmark and validate the impact before adding it to production? You can do it with Mongo Pilot, a smart MongoDB GUI:
Types of Indexes in MongoDB
| Type of index | Use case |
|---|---|
| Single field index | Most common. For filtering/sorting on one field. |
| Compound Index | For queries using multiple fields in a specific order. |
| Multikey Index | For indexing fields that contain arrays. |
| Text Index | For full-text search ($text, $search). Only for self-deployed MongoDB. Use Atlas Search instead |
| Hashed Index | For sharding use cases. |
| Wildcard Index | For dynamic keys in flexible schema. |
| TTL Index | For automatic expiry of documents (e.g., sessions, logs). |
How to Choose the Right MongoDB Index
- Start with your most common queries
- Use
.explain()or Mongo Pilot performance experiments to analyze - Avoid indexing everything : each index adds write overhead
- Don’t over-index : each index takes memory & slows writes
- Compound indexes > multiple single-field indexes (when used right)
- Sorts? Include them in your index if they come after a
find()
Now that you understand MongoDB indexing, why not test your knowledge? Take our timed MongoDB quiz and see how you rank against other developers!
TL;DR
- Indexes = faster reads, fewer scans
- Good indexes can improve query speed by 100× or more
- Mongo Pilot helps you test & visualize their impact instantly
