C100DBA · Question #89
As per the aggregation pipeline optimization concepts, if you have a $sort followed by a $match:
The correct answer is D. $match moves before $sort. MongoDB's aggregation pipeline optimizer automatically moves $match stages before $sort when possible, because filtering documents first reduces the number of records that need to be sorted - sorting is expensive, and doing it on fewer documents is far more efficient. Why the dis
Question
As per the aggregation pipeline optimization concepts, if you have a $sort followed by a $match:
Options
- AProviding these parameters in any order does not impact the performance
- B$sort moves before $match
- CMongoDB does not do any movements by default and will use the order provided
- D$match moves before $sort
How the community answered
(45 responses)- A11% (5)
- B2% (1)
- C7% (3)
- D80% (36)
Explanation
MongoDB's aggregation pipeline optimizer automatically moves $match stages before $sort when possible, because filtering documents first reduces the number of records that need to be sorted - sorting is expensive, and doing it on fewer documents is far more efficient.
Why the distractors are wrong:
- A is wrong because order absolutely matters for performance - processing fewer documents earlier is always better.
- B is wrong because moving
$sortbefore$matchwould mean sorting a larger dataset before filtering, which is the opposite of optimal. - C is wrong because MongoDB does reorder stages automatically as part of its pipeline optimization phase - it doesn't blindly execute in the order you write.
Memory tip: Think "filter before you sort" - just like you'd sort a stack of papers only after removing the irrelevant ones. MongoDB's optimizer applies the same common sense: $match moves early, $sort stays late.
Topics
Community Discussion
No community discussion yet for this question.