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.
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 })
Finally, remember that an index cannot cover a query if:
Any indexed field is an array
Any indexed field is a Subdocument
According to Tutorialspoint
Previous article: Reference Database in MongoDB
Next lesson: Query analysis in MongoDB
You should read it
- Index (Mong) in MongoDB
- Query Document in MongoDB
- The multiple-choice question set has an answer to Query P1
- How to have Siri respond to your voice when the iPhone screen is covered
- Action Query in Action 2016
- Multiple choice questions have a Query option
- Query analysis in MongoDB
- Set up Query Criteria in Access 2016
- What do you know about data queries?
- The bootcfg query command in Windows
- Why use Microsoft Power Query for Excel
- Capped Collection in MongoDB
Maybe you are interested
How to implement infinite scrolling and pagination with Next.js and TanStack Query
What is the unauthorized GraphQL query error that causes Facebook Messenger to not work?
The cost per search query with Google and Microsoft chatbots can cost 10 times more than a regular search query
How to access TPM Diagnostics tool to query security data on Windows 11
What is SQL Query Optimization... and Why Does It Matter?
ENCODEURL function - The function returns a query string with URL code in Excel