I have a collection with 250K documents and I want to find the last one inserted with a particular property "siteid" which is indexed. This is the query I am using.
db.getCollection('txnCollection').find({"siteid":"123456"}).limit(1).sort({"_id":-1})
If there is a record it is found quickly. If there isn't the performance is not quick enough circa 0.8s.
However if I run the query
db.getCollection('txnCollection').find({"siteid":"123456"}).limit(1)
The performance is really quick even if there is no document with siteid 123456.
It seems silly to run this query then if a record is returned to run the second query to get the record I want - ie. the last inserted one, but I cannot work out a way of doing anything better
For info when I run explain the result I get is
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "txn.txnCollection",
"indexFilterSet" : false,
"parsedQuery" : {
"siteid" : {
"$eq" : "123456"
}
},
"winningPlan" : {
"stage" : "SORT",
"sortPattern" : {
"_id" : -1
},
"limitAmount" : 1,
"inputStage" : {
"stage" : "KEEP_MUTATIONS",
"inputStage" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"siteid" : 1
},
"indexName" : "siteid_1",
"isMultiKey" : false,
"direction" : "forward",
"indexBounds" : {
"siteid" : [
"[\"123456\", \"123456\"]"
]
}
}
}
}
},
"rejectedPlans" : []
},
"serverInfo" : {
"host" : "XXXXX",
"port" : 27017,
"version" : "3.0.6",
"gitVersion" : "1ef45a23a4c5e3480ac919b28afcba3c615488f2"
},
"ok" : 1
}