7 Indexing for query performance
This chapter covers
- Understanding MongoDB query planner and execution plan
- Creating, deleting, and viewing MongoDB indexes
- Learning MongoDB index types
- Showing the ESR rule of thumb
- Measuring MongoDB Indexes Usage
Over years of work, I have encountered numerous instances where indexes were either not used correctly or not used at all. This is sub-optimal, as indexes allow for efficient query performance and overall database optimization.
In this chapter, I give you best practices for using indexes, rules of thumb, and methods for monitoring index usage and optimization.
Indexes are special data structures that store a small portion of the collection's data in an easily traversable B-tree form. An index orders the values of specific fields, supporting efficient equality matches and range-based queries. MongoDB can also use the index to return sorted results.
Without indexes, MongoDB must scan every document in a collection to return query results. This process is very poor in terms of performance. A suitable index limits the number of documents that need to be scanned.
While indexes improve query performance, they can negatively impact write operations. In collections with a high write-to-read ratio, indexes can be costly as each insert operation must update the indexes.