Latest web development tutorials

MongoDB covering index query

The official MongoDB document description, covering the following query is a query:

  • All query fields are part of the index
  • All the fields in the same query returns the index

Since all appear in the query field is part of the index, MongoDB data files without having to retrieve the entire match query terms and return query results using the same index.

Because the index reside in RAM, the access to data than to read data much faster by scanning documents from the index.


Use a covering index query

To test cap index query, use the following set of users:

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

We create a joint index users collection, field 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's not going to file for a database. Instead, it extracts the data from the index, which is very fast data query.

Since our index does not include the _id field, _id will be returned by default in the query, we can concentrate exclude it in MongoDB query results.

The following examples are not ruled _id, the query will not be covered:

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

Finally, if the following query, the query can not use the index covering:

  • All index field is an array
  • All sub-index field is a document