Hello everyone,
I have a collection with 10 documents. This is the result of my query using aggregation
> db.system.profile.find({"op":"command"}).pretty()
{
"op" : "command",
"ns" : "test.bar3",
"command" : {
"aggregate" : "bar3",
"pipeline" : [
{
"$match" : {
"from" : "0x222222",
"to" : "0x333333"
}
},
{
"$sort" : {
"_id" : -1
}
}
],
"cursor" : {
},
"lsid" : {
"id" : UUID("7712d372-c98a-472a-9020-94072f40dd84")
},
"$db" : "test"
},
"keysExamined" : 10,
"docsExamined" : 10,
"cursorExhausted" : true,
"numYield" : 0,
"nreturned" : 5,
"queryHash" : "DE146C9F",
"planCacheKey" : "DE146C9F",
"locks" : {
"ReplicationStateTransition" : {
"acquireCount" : {
"w" : NumberLong(1)
}
},
"Global" : {
"acquireCount" : {
"r" : NumberLong(1)
}
},
"Database" : {
"acquireCount" : {
"r" : NumberLong(1)
}
},
"Collection" : {
"acquireCount" : {
"r" : NumberLong(1)
}
},
"Mutex" : {
"acquireCount" : {
"r" : NumberLong(1)
}
}
},
"flowControl" : {
},
"responseLength" : 1028,
"protocol" : "op_msg",
"millis" : 0,
"planSummary" : "IXSCAN { _id: 1 }",
"ts" : ISODate("2020-03-19T08:31:11.480Z"),
"client" : "127.0.0.1",
"allUsers" : [ ],
"user" : ""
}
On $match
stage, there are 5 documents satisfy filter condition. The following $sort
stage sorts the documents with "_id"
, so the "planSummary"
is "IXSCAN { _id: 1 }"
.
Why the number of "keysExamined"
is 10 but not 5?? In my opinion, $match
will scan all documents in collections, and then get 5 documents. So $sort
stage should sort those 5 documents.
I just want to know the stage execution sequence. Is $match
before $sort
or $sort
before $match
?
Thanks in advance!!!
Version: v4.2.3 Mac osx