MongoDB Covered Query
The official MongoDB documentation states that a covered query is one where:
- All query fields are part of an index
- All fields returned in the query are in the same index
Since all fields appearing in the query are part of an index, MongoDB does not need to search the entire data documents to match query conditions and return query results using the same index.
Because indexes exist in RAM, getting data from the index is much faster than reading data by scanning documents.
Use Covered Queries
To test covered 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 the 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 in version 5.0; use `createIndex()` instead.
Now, this index covers the following query:
>db.users.find({gender:"M"},{user_name:1,_id:0})
That is, for the above query, MongoDB will not search 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, the following queries cannot use covered queries:
- All index fields are an array
- All index fields are a subdocument