The execution sequence is always $match
followed by $sort
(irrespective of the order of these stages). The optimizer makes sure that the sort stage has documents after they are filtered (that would be less number of documents than the input to the match stage).
More details at: $sort + $match Sequence Optimization
There might be some index on the collection bar3
, and this is affecting the $match
stage, I think. You can post the details.
If possible, please run the explain for the aggregation query with “executionStats” mode.