0
0
MongoDBquery~5 mins

Covered queries with indexes in MongoDB

Choose your learning style9 modes available
Introduction
Covered queries help MongoDB find data quickly by using only the index without looking at the full documents.
When you want to speed up read operations on a collection.
When you only need a few fields from documents, not the whole document.
When you want to reduce the amount of data MongoDB reads from disk.
When you want to improve performance for frequent queries on specific fields.
Syntax
MongoDB
db.collection.createIndex({ field1: 1, field2: 1 })
db.collection.find({ field1: value }, { field1: 1, field2: 1, _id: 0 })
The index must include all fields used in the query filter and the fields returned in the result.
Exclude the _id field in the projection if it is not part of the index to keep the query covered.
Examples
This query uses an index on category and price to return only those fields without reading full documents.
MongoDB
db.products.createIndex({ category: 1, price: 1 })
db.products.find({ category: "books" }, { category: 1, price: 1, _id: 0 })
A simple covered query that uses an index on username and returns only the username field.
MongoDB
db.users.createIndex({ username: 1 })
db.users.find({ username: "alice" }, { username: 1, _id: 0 })
Sample Program
This query finds orders for customer 12345 and returns only customerId and status fields using the index.
MongoDB
db.orders.createIndex({ customerId: 1, status: 1 })
db.orders.find({ customerId: 12345 }, { customerId: 1, status: 1, _id: 0 })
OutputSuccess
Important Notes
Covered queries reduce disk I/O because MongoDB does not fetch the full document.
Make sure the index covers all fields in the query filter and projection to benefit from covered queries.
If you include fields in the projection that are not in the index, MongoDB will fetch the full document.
Summary
Covered queries use indexes to return data without reading full documents.
They improve query speed and reduce resource use.
Create indexes that include all fields you filter and return.