8. Covered Queries and Projection

A covered query can be satisfied using index keys without fetching the full collection documents. The index must contain the fields needed to evaluate the query and return the requested projection, subject to MongoDB's coverage rules.

For example, if an API filters by status and returns only status and customerId, a compound index containing those fields may make coverage possible. The exact index should be designed around the query's filter and projection.

Coverage can reduce document fetches, but adding fields to an index increases its size and write-maintenance cost. Do not create huge indexes solely to cover every possible API response.

Use explain execution statistics to check whether document fetches occur and whether the chosen plan is actually covered.

Coverage has requirements

The index must provide all fields needed by the query and projection. _id is normally returned unless excluded, so projection details can affect coverage.

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

db.orders.find(
  { status: "delivered" },
  { _id: 0, status: 1, customerId: 1 }
).explain("executionStats");
Key Takeaways
  • A covered query can avoid fetching full documents.
  • The index must contain the required filter and result fields.
  • Coverage trades reduced fetches for a larger maintained index.
  • Confirm coverage using explain output.
Knowledge Check

What is a key property of a covered query?