MongoDB Covered Queries - MongoDB

What is the useof covered queries in MongoDB?

In this chapter, we will explain you about covered queries.

Whatis a Covered Query?

Based on the official MongoDB documentation, a covered query is a query in which

  • All the fields in the query are part of an index.
  • All the fields returned in the query are in the same index.

As all the fields present in the query are part of an index, MongoDB will match the query conditions and will return the result using same index without even looking into the documents. As indexes are present in RAM, fetching data from indexes is quicker than fetching data by scanning documents.

Using Covered Queries

To test covered queries, consider below document in the users collection

Let’s first create a compound index for the users collection on the fields gender and user_name using the following query

Now, this index will cover below query

This says that for the above query, MongoDB will not look into database documents. Rather it will fetch the needed data from indexed data which is very fast.
As our index does not include _id field, we have explicitly excluded it from result set of our query, as MongoDB by default returns _id field in every query. Therefore the below query will not have been covered inside the index created above

Finally note that an index cannot cover a query if

  • Any of the indexed fields is an array
  • Any of the indexed fields is a sub document

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics