7 Indexing for query performance

 

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.

7.1 MongoDB query planner

7.1.1 Viewing query plan cache information

7.1.2 MongoDB plan cache purges

7.2 Supported index types

7.2.1 Creating single field indexes

7.2.2 Understanding compound indexes

7.2.3 Using multikey indexes

7.2.4 Using text indexes

7.2.5 Creating wildcard indexes

7.2.6 Geospatial indexes

7.2.7 Hashed indexes

7.3 Dropping indexes

7.4 MongoDB index attributes

7.4.1 Partial indexes

7.4.2 Sparse indexes

7.4.3 Time-to-live indexes

7.4.4 Hidden indexes

Summary