To reproduce this behavior:
db.c.insertMany([\{a: 1}, \{a: 2}, \{a: 3}])
Now run:
db.c.aggregate([{$addFields:{"diff": {$subtract: [100, "$a"]}}},{$match: {"diff": {$lte: 12}}}]);
The slow query log for this is:
"Slow query","attr":{"type":"command","ns":"test.m","appName":"MongoDB Shell","command":{"aggregate":"m","pipeline":[{"$addFields":{"hourDiff":{"$subtract":[100,"$a"]}}},{"$match":{"hourDiff":{"$lte":12}}}],"cursor":{},"lsid":{"id":{"$uuid":"dd4183fa-b0c3-420e-b0c7-54508c7efa96"}},"$db":"test"},"planSummary":"COLLSCAN","planningTimeMicros":798,"keysExamined":0,"docsExamined":3,"fromPlanCache":true,"cursorExhausted":true,"numYields":0,"nreturned":3,"queryHash":"E475932B","planCacheKey":"14AB0B81","queryFramework":"sbe","reslen":95,"locks":{"FeatureCompatibilityVersion":{"acquireCount":{"r":2}},"Global":{"acquireCount":{"r":2}}},"storage":{},"cpuNanos":3908578,"remote":"127.0.0.1:56992","protocol":"op_msg","durationMillis":3}}
This will give nReturned = 3 which is the total number of docs and not the number of docs matched. Note that this does not happen when there is only a match stage. It happens if addFields comes before match (I haven't checked other stages that could potentially cause the same issue)