$match and $group
Filter documents early in a pipeline with $match, and summarize them with $group and its accumulator operators.
$match: Filtering in a Pipeline
$match filters documents using the exact same query syntax as find(), and is almost always the first stage in a pipeline — filtering early reduces how many documents later, more expensive stages need to process.
db.orders.aggregate([ { $match: { status: "completed", total: { $gte: 50 } } },]);$group: Summarizing Documents
$group collapses many documents into one summary document per distinct value of a chosen field, specified via _id.
db.orders.aggregate([ { $group: { _id: "$status", count: { $sum: 1 } } },]);Click Run to see what this code prints.
Accumulator Operators
| Operator | Computes |
|---|---|
| $sum | A running total (use $sum: 1 to simply count documents) |
| $avg | The average of a numeric field |
| $min / $max | The smallest / largest value |
| $push | Collects values into an array |
| $first / $last | The first / last value encountered in the group (order-dependent) |
db.orders.aggregate([ { $group: { _id: "$customerId", totalSpent: { $sum: "$total" }, averageOrder: { $avg: "$total" }, orderIds: { $push: "$_id" }, }, },]);Grouping by Multiple Fields
Passing an object as _id groups by the combination of multiple fields at once.
db.orders.aggregate([ { $group: { _id: { customerId: "$customerId", status: "$status" }, count: { $sum: 1 } } },]);Common Beginner Mistakes
Filtering as early as possible reduces the number of documents every subsequent stage has to process — always $match first when the filter doesn't depend on a later computed value.
{ $sum: total } is invalid — field references inside aggregation expressions need a leading $: { $sum: "$total" }.
FAQs
Yes — a second $match after a $group is common, filtering on the newly computed summary fields (the equivalent of SQL's HAVING clause).
You get a single summary document covering the entire collection — a common pattern for computing an overall total or average.
Summary
$match filters early, and $group with accumulator operators summarizes documents into computed results. Next, you'll learn $project, $sort, and $limit for reshaping and ordering pipeline output.