Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MongoDB Covered Index Query

MongoDB Covered Index Query

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

Since all fields appearing in the query are part of an index, MongoDB does not need to search the entire data document to match query conditions and return results using the same index.

Because indexes exist in RAM, retrieving data from an index is much faster than reading data by scanning documents.


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 in the users collection, with fields gender and user_name:



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

**Note:** Versions before 5.0 can use db.collection.ensureIndex(), but ensureIndex() has been removed after version 5.0, use createIndex() instead.

Now, this index will cover the following queries:



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

That is, for the above queries, MongoDB will not look in the database files. Instead, it extracts 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 queries; 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, the following queries cannot use covered index queries: