English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MongoDB Covered Query

In this chapter, we will learn about covered queries.

What is a covered query?

According to the official MongoDB documentation, covered queries are such queries where-

  • All the fields in the query are part of the index.

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

Since all the fields in the query are part of the index, MongoDB will match the query conditions and return the results using the same index without actually looking inside the documents. Since the index exists in RAM, it is much faster to get data from the index compared to scanning the documents to get data.

Using covered queries

To test the queries that cover the range, please seesersThe following documents in the collection-

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

We will first use the following query to create a compound index on the gender and user_name fields for the users collection–

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

Now, the index will cover the following queries-

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

That is, for the above query, MongoDB will not view the database documents. Instead, it will obtain the required data from the index data, which is very fast.

Since the index does not include_idField, so we have explicitly excluded it from the query results, because MongoDB defaults to returning the _id field in each query. Therefore, the following query will not be included in the index created above–

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

Finally, remember that if, the index cannot cover the query

  • Any indexed field is an array

  • Any indexed field is a sub-document