1. Why Indexes Matter
The problem indexes solve
Without a suitable index, MongoDB may need to inspect many or all documents in a collection to answer a query. This is commonly called a collection scan. As a collection grows, scanning every document can increase latency and resource use.
An index is a data structure that stores selected field values in an order that helps MongoDB locate matching documents or return them in a useful order. Indexes can reduce the amount of data examined, support sorting, enforce uniqueness, and support special query types.
Indexes are not free. They consume storage and memory, take time to build, and must be maintained when indexed fields change. A collection with too many indexes can have slower writes and greater resource usage.
The objective is not to index every field. It is to choose a small, useful set of indexes that support real query patterns and constraints.
MongoDB's planner decides which plan is appropriate. An existing index is not necessarily selected, and an index may not help a query that returns a large fraction of the collection.
db.orders.find({ status: "delivered" });
// Create an index that may support this filter.
db.orders.createIndex({ status: 1 });
db.orders.find({ status: "delivered" }).explain("executionStats");- Indexes can reduce documents examined and support sorting.
- Indexes consume storage and increase write-maintenance work.
- Design indexes around actual query patterns.
- Use explain output to verify whether an index helps.
What is a common cost of adding an index?