problem description
There are two indexes in mongo, the first is a single-field index of the {_ id} field, and the second index is a composite index composed of {chat_id, _ id}. When I use the query
db.collection.find ({"chat_id": ObjectId ("*"), "the_time": {"$lt": ISODate ("2010-01-01T00:00:00Z")}}). Sort ({"the_time":-1}). Explain ("executionStats")
, why do I get the following results
......
"winningPlan" : {
"stage" : "SORT",
"sortPattern" : {
"the_time" : -1
},
"inputStage" : {
"stage" : "SORT_KEY_GENERATOR",
"inputStage" : {
"stage" : "FETCH",
"filter" : {
"the_time" : {
"$lt" : ISODate("2010-01-01T00:00:00Z")
}
},
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"chat_id" : 1,
"_id" : 1
},
"indexName" : "chat_id_1__id_1"
......
Why is a composite index composed of {chat_id, _ id} used?
the composite index I"ve learned about is like this
Theindex prefix refers to a subset of the composite index
{ "item": 1, "location": 1, "stock": 1 }
{ item: 1 }
{ item: 1, location: 1 }
MongoDB
item
item + location
item + location + stock
item + location()
location
stock
location + stock
question 1: is it possible that in the composite index {chat_id, _ id}, even if the query used is {chat_id, the_time}, the the_time field is not in the composite index, but the chat_id is in the composite index, so will you take this composite index?
question 2: in addition, I added an extra index {chat_id,third_field} and still queried {chat_id,the_time}. The final analysis result is the {chat_id,third_field} index, but not the {chat_id, _ id} index. What is the strategy of mongo in index selection?