nerdexam
MongoDB

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

Performance Tuning

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)
  • A
    11% (5)
  • B
    2% (1)
  • C
    7% (3)
  • D
    80% (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 $sort before $match would 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

#aggregation pipeline#$sort#$match#pipeline optimization

Community Discussion

No community discussion yet for this question.

Full C100DBA Practice