YouTip LogoYouTip

Mongodb Covered Queries

MongoDB Covered Index Queries | Tutorial

Tutorial -- Learning is not just about technology, but also about dreams!

MongoDB Tutorial

MongoDB Advanced Tutorial

MongoDB Database References

MongoDB Query Analysis

MongoDB Covered Index Queries

The official MongoDB documentation states that a covered query is one where:

  • All the fields in the query are part of an index
  • All the fields returned in the query results are in the same index

Since all the fields present in the query are part of the index, MongoDB does not have to look through the entire data documents to match the query conditions and return the results using the same index.

Since indexes exist in RAM, fetching data from the index is much faster than scanning through the documents to read the data.


Using Covered Index Queries

To test covered index queries, 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 compound index on the users collection with fields gender and user_name:

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

Note: For versions before 5.0, you can use db.collection.ensureIndex(), but ensureIndex() has been removed in version 5.0 and later. Use createIndex() instead.

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 go to the database files. Instead, it will extract data from the index, which is a very fast data query.

Since our index does not include the _id field, _id is returned by default in the query. We can exclude it from the MongoDB query result set.

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

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

Finally, covered index queries cannot be used for the following types of queries:

  • All indexed fields are arrays
  • All indexed fields are sub-documents

← Mongodb Analyzing QueriesMongodb Database References β†’