2. How MongoDB Indexes Work Conceptually

MongoDB's standard indexes use ordered index structures. Conceptually, an index maps indexed field values to references to matching documents. This allows the query engine to navigate relevant portions of the index instead of examining every document.

For an index on status, the index entries are ordered by status value. A query for status: "delivered" can navigate to the relevant index range and then fetch matching documents as needed.

An index is not a copy of the entire collection. Ordinary indexes store indexed keys and references, with special behavior depending on the index type. If the query needs fields not present in the index, MongoDB may need to fetch documents from the collection.

The exact physical implementation and query-plan details are version- and engine-dependent. For practical tuning, focus on the observed plan, keys examined, documents examined, and returned results rather than assuming every index access has the same cost.

Code Example
db.orders.createIndex({ status: 1 });

db.orders.find({ status: "delivered" })
  .explain("executionStats");
Key Takeaways
  • Indexes store ordered keys and references to matching records.
  • An index scan can still require document fetches.
  • Execution statistics reveal how much work a plan performs.
  • Avoid assuming that every index scan is automatically efficient.
Knowledge Check

Why might MongoDB fetch collection documents after using an index?