In this bankruptcy, we are able to study included queries.
What is a Covered Query?
As in keeping with the legit MongoDB documentation, a blanketed query is a query in which −
- All the fields inside the question are part of an index.
- All the fields returned within the query are within the equal index.
Since all the fields present in the question are part of an index, MongoDB fits the question situations and returns the end result using the equal index without genuinely searching in the files. Since indexes are found in RAM, fetching records from indexes is a good deal quicker in comparison to fetching statistics by means of scanning files.
Using Covered Queries
To take a look at covered queries, take into account the subsequent record inside the customers series −
{
"_id": ObjectId("53402597d852426020000003"),
"contact": "987654321",
"dob": "01-01-1991",
"gender": "M",
"name": "Tom Benzamin",
"user_name": "tombenzamin"
}
We will first create a compound index for the customers collection at the fields gender and user_name the usage of the subsequent question −
>db.users.createIndex({gender:1,user_name:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Now, this index will cover the following question −
>db.users.find({gender:"M"},{user_name:1,_id:0})
{ "user_name" : "tombenzamin" }
That is to say that for the above query, MongoDB could not cross searching into database files. Instead it would fetch the desired information from listed statistics which could be very speedy.
Since our index does not include _id subject, we've explicitly excluded it from result set of our question, as MongoDB via default returns _id area in each query. So the following query could not have been included in the index created above −
>db.users.find({gender:"M"},{user_name:1})
{ "_id" : ObjectId("53402597d852426020000003"), "user_name" : "tombenzamin" }
Lastly, take into account that an index can not cowl a question if −
Any of the listed fields is an array
Any of the indexed fields is a subdocument