MongoDB Overlay Index Query
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.
In order to test the cover index query, use the following MyCol collection:
{"_id": 1, "name": "Tom", "Sex": "Male", "score": +, "age": 34}
{"_id": 2, "name": "Jeke", "Sex": "Male", "score": +, "age": 24}
{"_id": 3, "name": "Kite", "sex": "female", "score": +, "age": 36}
{"_id": 4, "name": "Herry", "Sex": "Male", "score": +, "age": 56}
{"_id": 5, "name": "Marry", "sex": "female", "score": +, "age": 18}
{"_id": 6, "name": "John", "Sex": "Male", "score": +, "age": 31}
We create a federated index in the Users collection, which is sex and score:
Db.mycol.ensureIndex ({sex:1, score:1})
The index now overwrites the following query:
Db.mycol.find ({sex: ' Male '},{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.mycol.find ({sex: ' Male '},{name:1})
Finally, if all the indexed fields are an array, you cannot use the Overwrite index query.
MongoDB Overlay Index Query