Q22: Explain $match, $group, and $project pipeline stages.
$match: Filters documents to allow only those matching specified conditions to pass (place$matchfirst to leverage indexes).$group: Groups input documents by a specified_idexpression and applies accumulator operators ($sum,$avg,$push).$project: Reshapes documents by adding, removing, or renaming fields.
Basic Aggregation Pipeline Example
db.orders.aggregate([
{ $match: { status: 'completed' } }, // 1. Filter
{ $group: {
_id: '$customerId',
totalSpent: { $sum: '$amount' }, // 2. Group & Sum
orderCount: { $sum: 1 }
}},
{ $sort: { totalSpent: -1 } } // 3. Sort
]);Filters completed orders, groups by customer ID, calculates total expenditure, and orders results.
Key Takeaways
Place
$matchas early as possible to reduce document volume.$groupperforms SQLGROUP BYaggregations.
Knowledge Check
Why should $match stages be placed at the very beginning of an aggregation pipeline?