What is a covered query in MongoDB?

Instruction: Define a covered query and explain its benefits in MongoDB.

Context: This question aims to test the candidate's knowledge of MongoDB's query optimization techniques, specifically the use of indexes to fulfill a query without accessing the documents.

Updated

Official answer

A covered query can obtain both its filtering information and returned fields from an index without fetching collection documents. The query and projection must be supported by the same usable index; having separate indexes for each field is not sufficient by itself.

For a collection with an appropriate index on status and name, this illustrative query can be covered when its other requirements are met:

db.users.find({status: "active"}, {name: 1, _id: 0})

Explicitly excluding _id matters when _id is absent from the covering index. Null comparisons, array projections/multikey restrictions, collation and sharding requirements can prevent coverage. On a sharded collection, the necessary shard-key fields also matter.

Inspect explain with executionStats. A covered plan should avoid a document FETCH and show zero documents examined for that query; confirm the actual winning plan rather than inferring coverage from the index definition alone. Check returned values against the intended semantics.

Coverage can reduce document I/O, but it does not guarantee all index pages are in RAM or make an index free. Wider indexes increase storage and write cost. Measure the benefit on representative workloads before adding fields solely for coverage.

MongoDB covered queries

Related Questions