Database indexes are one of the simplest ways to improve query performance.
They can also become one of the easiest ways to waste resources if used incorrectly.
What Is an Index?
Imagine a 500-page book.
If you want to find every mention of "MongoDB", you could read every page.
Or you could use the index at the back of the book.
A database index works similarly.
Instead of scanning every record, the database can use an optimized data structure to locate matching records faster.
Example
Suppose you frequently search users by email:
db.users.findOne({
email: "alex@example.com"
});
Creating an index on email can make this query much more efficient:
db.users.createIndex({
email: 1
});
Why Not Index Everything?
Indexes have costs.
When data changes, indexes may also need to be updated.
That means more:
- Storage
- Memory usage
- Write overhead
- Maintenance
Therefore, indexes should be created around actual query patterns.
Compound Indexes
Sometimes queries use multiple fields:
db.orders.find({
userId: "123",
status: "completed"
});
A compound index could help:
db.orders.createIndex({
userId: 1,
status: 1
});
The correct index depends on how the application queries the database.
Measure Before Optimizing
Don't blindly create indexes.
First identify slow queries using database profiling and query execution plans.
Optimization should be based on evidence.
Final Thoughts
Indexes are not magic performance switches.
They are tools that trade additional storage and write overhead for faster reads.
Understanding that trade-off is an important database skill.
Top comments (0)