MongoDB - Covered Queries

MongoDB - Covered Queries

What is a closed request?

According to the official MongoDB documentation, a covered query is a query where:

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

Because all fields present in a query are part of the index, MongoDB matches the query terms and returns the result using the same index without actually looking at the documents. Because indexes are in-memory, fetching data from indexes is much faster than fetching data by scanning documents.

Using Covered Requests

To check the covered requests, consider the following document in the users collection −

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

First, we will create a composite index on a collection of users by gender gender and username 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 })

That is, for the above query, MongoDB will not look for database documents. Instead, it will extract the necessary data from the indexed data, which is very fast.

Because our index doesn't include the _id field , we've explicitly excluded it from our query result set because MongoDB returns the _id field in every query by default. Thus, the following query would not be covered inside the index created above −

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

Lastly, remember that an index cannot cover a query if −