Home >>MongoDB Tutorial >MongoDB Covered Queries

MongoDB Covered Queries

What is a Covered Query?

A covered query is a query, according to the official MongoDB documents, in which −

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

Since all the fields present in the query are part of an index, MongoDB matches the conditions of the query and returns the result without actually looking into the documents using the same index. As indexes are present in RAM, it is much easier to fetch data from indexes compared to scanning documents to fetch data.

Using Covered Queries

Consider the following document in the user collection to test covered queries –

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

First, we create a compound index for the user set using the following query on the gender and user name fields.

>db.users.createIndex({gender:1,user_name:1})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}

Now, this index will cover the following query −

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

That is to suggest that MongoDB wouldn't look into database documents for the above query. Instead, it can very easily fetch the required data from indexed data.

Since our index does not contain the id field, we have specifically excluded it from our query's result set, as MongoDB returns the id field in each query by default. So the following query inside the index created above would not have been covered.

>db.users.find({gender:"M"},{user_name:1})
{ "_id" : ObjectId("53402597d852426020000003"), "user_name" : "tombenzamin" }

Finally, remember that a query should not be covered by an index if −

  • Any of the fields indexed is an array
  • A subdocument for each of the indexed fields is

No Sidebar ads