Table of Contents
Covered Query in Mongodb is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.
What is Covered Query?
In the official MongoDB Documentation, a Covered Query is a query in which:
All fields in the query are part of an index and
All fields returned in the query are in the same index.
When all fields in the query are part of the index, MongoDB connects query conditions and returns the result by using the same index without looking inside the Document. When indexes are present in RAM, retrieving data from indexes is faster when compared to retrieving data by scanning all documents.
Use Covered Query in MongoDB
To study Covered Query, you follow the following Document in the user collection:
{ "_id" : ObjectId ( "53402597d852426020000002" ), "contact" : "987654321" , "dob" : "01-01-1991" , "gender" : "M" , "name" : "Tom Benzamin" , "user_name" : "tombenzamin" }
First, we create a complex index for users collection on the gender and user_name fields using the following query:
> db . users . ensureIndex ({ gender : 1 , user_name : 1 })
Now, this index will cover the following query:
> db . users . find ({ gender : "M" },{ user_name : 1 , _id : 0 })
It can be said that, with the above query, MongoDB will not go into searching for documents in the database. Instead, it will retrieve the necessary data from indexed data, which will make the process much faster.
When our index does not include the _id field, we explicitly exclude it from the result set of the query, because with MongoDB, by default it will return the _id field in each query. Therefore, the following query will not be covered within the index created above:
> db . users . find ({ gender : "M" },{ user_name : 1 })
Next lesson: Query analysis in MongoDB
FAQ
What is Covered Query?
In the official MongoDB Documentation, a Covered Query is a query in which:
What should you know about use Covered Query in MongoDB?
To study Covered Query, you follow the following Document in the user collection:
What is Covered Query in Mongodb?
What is Covered Query? In the official MongoDB Documentation, a Covered Query is a query in which: All fields in the query are part of an index and All fields returned in the query are in the same index.
Reader Comments 0
Sign in with email or Google to join the discussion.