The official MongoDB documentation shows that the overwrite query is the following query:
- All query fields are part of the index
- All the query return fields are in the same index
Because all fields that appear in the query are part of the index, MongoDB does not need to retrieve matching query criteria throughout the data document and return query results that use the same index.
Because the index exists in RAM, getting data from the index is much faster than reading the data by scanning the document.
Using the Overwrite index query
In order to test the Overwrite 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 federated indexes in the Users collection, fields Gender and user_name:
>db.users.ensureindex ({gender:1,user_name:1})
The index now overwrites the following query:
>db.users.find ({gender: "M"},{user_name:1,_id:0})
In other words, for the above query, MongoDB will not go to the database file to find. Instead, it extracts the data from the index, which is a very fast data query.
Since the _id field is not included in our index, _ID is returned by default in the query, and we can exclude it from the query result set in MongoDB.
The following instance does not exclude _id and the query will not be overwritten:
>db.users.find ({gender: "M"},{user_name:1})
Finally, if the query is the following, you cannot use the Overwrite index query:
- All indexed fields are an array
All indexed fields are a sub-document
MongoDB Overlay Index Query