MongoDB Covered Index Query
The official MongoDB documentation states that a covered query is a query where:
- All the fields in the query are part of an index
- All the fields returned in the query are in the same index
Since all the fields appearing in the query are part of the index, MongoDB does not need to retrieve the matching query conditions and return results from the entire data document. Instead, it uses the same index for both operations.
Because the index resides in RAM, fetching data from the index is much faster than reading data by scanning the documents.
Using Covered Index Query
To test a covered 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 compound index on the users
collection for the fields gender
and user_name
:
>db.users.createIndex({gender:1,user_name:1})
Note: Prior to version 5.0, db.collection.ensureIndex()
could be used, but ensureIndex()
has been removed in version 5.0 and replaced with createIndex()
.
Now, this index will cover the following query:
>db.users.find({gender:"M"},{user_name:1,_id:0})
This means that for the above query, MongoDB will not look into the database files. Instead, it will extract the data from the index, which is a very fast data retrieval process.
Since our index does not include the _id
field, and _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 a covered index:
- All indexed fields are arrays