This chapter covers
- Understanding MongoDB’s query planner and execution plan
- Creating, deleting, and viewing MongoDB indexes
- Learning MongoDB index types
- Understanding the Equality, Sort, Range rule of thumb
- Measuring MongoDB index use
Over years of work, I have encountered numerous instances in which indexes were not used correctly or at all. This is suboptimal, as indexes allow 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 use 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.
Although indexes improve query performance, they can negatively affect write operations. In collections with a high write-to-read ratio, indexes can be costly because each insert operation must update the indexes.