Covered Query in MongoDB

When all fields in the query are part of the index, MongoDB connects query conditions and returns the result by using the same index without looking inside the Document. When indexes are present in RAM, retrieving data from indexes is faster when compared to retrieving data by scanning all documents.

What is Covered Query?

In the official MongoDB Documentation, a Covered Query is a query in which:

All fields in the query are part of an index and

All fields returned in the query are in the same index.

When all fields in the query are part of the index, MongoDB connects query conditions and returns the result by using the same index without looking inside the Document. When indexes are present in RAM, retrieving data from indexes is faster when compared to retrieving data by scanning all documents.

Use Covered Query in MongoDB

To study Covered Query, you follow the following Document in the user collection:

 { "_id" : ObjectId ( "53402597d852426020000002" ), "contact" : "987654321" , "dob" : "01-01-1991" , "gender" : "M" , "name" : "Tom Benzamin" , "user_name" : "tombenzamin" } 

First, we create a complex index for users collection on the gender and user_name fields using the following query:

 > db . users . ensureIndex ({ gender : 1 , user_name : 1 }) 

Now, this index will cover the following query:

 > db . users . find ({ gender : "M" },{ user_name : 1 , _id : 0 }) 

It can be said that, with the above query, MongoDB will not go into searching for documents in the database. Instead, it will retrieve the necessary data from indexed data, which will make the process much faster.

When our index does not include the _id field, we explicitly exclude it from the result set of the query, because with MongoDB, by default it will return the _id field in each query. Therefore, the following query will not be covered within the index created above:

 > db . users . find ({ gender : "M" },{ user_name : 1 }) 

Finally, remember that an index cannot cover a query if:

Any indexed field is an array

Any indexed field is a Subdocument

According to Tutorialspoint

Previous article: Reference Database in MongoDB

Next lesson: Query analysis in MongoDB

3.8 ★ | 5 Vote