|
Another stage that doesn't change the count is $sort. We could recognize whether or not a $group uses order-sensitive accumulators ($first, $push). Since we consider $sum / $add to be commutative and associative, we could eliminate the $sort in a pipeline like [{$sort ...} {$group: {_id: null, n: {$sum:1}}}].
|
|
I think this could be done by changing $count to be a concrete stage instead of an alias for $group $project. When
stages like $addFields and $project run their doOptimize function, they will see a $count ahead and remove themselves from the pipeline. Then inside the $count doOptimize, we remove the $count from the pipeline and add $group $project. So $count will always result in a $group $project, but is a concrete type (although it will never show up in a pipeline once optimization is done).
I think this would give the same effect as what we have now, except that stages can optimize if they see a $count.
Also it looks like $graphLookup is another stage that does not change the document count.
|