MongoDB tutoria...login
MongoDB tutorial
author:php.cn  update time:2022-04-21 17:49:03

MongoDB coverage index query


The official MongoDB documentation states that the coverage query is the following query:

  • All query fields are part of the index

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

Since all fields that appear in the query are part of the index, MongoDB eliminates the need to search the entire data document for matching query conditions and return query results using the same index.

Because the index exists in RAM, getting data from the index is much faster than reading the data by scanning the document.


Using covering index query

In order to test the covering index query, use the following users collection:

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

We create a joint index in the users collection with the fields gender and user_name:

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

Now, the 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 in the database file. Instead, it pulls data from the index, which is a very fast data query.

Since our index does not include the _id field, _id will be returned by default in the query, and we can exclude it from the MongoDB query result set.

The following example does not exclude _id, and the query will not be covered:

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

Finally, if it is the following query, the covering index query cannot be used:

  • All index fields are an array

  • All index fields are a subdocument

php.cn