In MongoDB, a covered query is a query that is able to fully utilize an index to retrieve all necessary data without having to evaluate documents. Specifically, a covered query means that all the fields required for projection or sorting are contained within the index keys, and there is no need to fetch additional documents from disk to satisfy these operations.
When a covered query is executed, MongoDB can utilize the index’s compact structure to retrieve only the data needed for the query without requiring additional scanning of the entire collection. This has a significant impact on the performance of the query.
For example, let’s consider the following query:
db.users.find({age: {$gt: 18}}, {_id: 0, name: 1, age: 1}).sort({age: 1})
If there is a compound index on ‘age‘ and ‘name‘, that includes all the fields in the query, then this query can be fully satisfied by the index, and there’s no need for MongoDB to evaluate any documents.
In contrast, if there is no appropriate index, MongoDB would have to scan the entire collection to evaluate each document, and then sort and project as needed. This can be very slow, especially if the collection is large.
Thus, covering queries can improve the performance of MongoDB queries by minimizing the amount of data that needs to be pulled from the disk and boosting query speeds when used appropriately.