Problem Statement
What is the recommended order for aggregation stages to optimize performance?
Explanation
Place dollar match stages as early as possible in the pipeline to filter documents before expensive operations like dollar group or dollar sort. This reduces the amount of data processed by subsequent stages.
Additionally, place dollar project or dollar addFields after grouping if you only need to transform the final results. Use dollar sort after dollar match and dollar group when possible. MongoDB can sometimes optimize the pipeline automatically, but following these patterns ensures better performance.
Code Solution
SolutionRead Only
// Optimized pipeline
db.orders.aggregate([
{ $match: { status: "completed" } }, // Filter first
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }, // Sort grouped results
{ $limit: 10 } // Limit final output
])