Q22: Explain $match, $group, and $project pipeline stages.

  • $match: Filters documents to allow only those matching specified conditions to pass (place $match first to leverage indexes).
  • $group: Groups input documents by a specified _id expression 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 $match as early as possible to reduce document volume.

  • $group performs SQL GROUP BY aggregations.

Knowledge Check

Why should $match stages be placed at the very beginning of an aggregation pipeline?