Typorithm · easy

$match & $group

mongo-match-groupmongodbpipelinefilteraccumulators
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn $match & $group

0%

Aggregation

An aggregation pipeline runs documents through ordered stages. $match filters first, then $group buckets by a key and runs accumulators like $sum and $avg over each bucket.

aggregate() takes an array of stages, and each document flows through them in order, like a Unix pipe.

$match filters documents up front so the heavier stages downstream see fewer of them — it is the cheapest place to cut data.

$group collapses documents that share an _id, and accumulators such as $sum, $avg, and $count compute one value per bucket.

01

$match filters like a WHERE clause.

02

$group buckets by its _id key.

03

$sum / $avg / $count accumulate per bucket.

db.orders.aggregate([{ $match: { status: "paid" } }, { $group: { _id: "$customerId", total: { $sum: "$amount" } } }])

Read the implementation

Connect each part of the code to the concept before you type.

1. Filter stage

$match keeps only documents that satisfy the condition, like a WHERE clause, and should run early so later stages process fewer docs.

{ $match: { status: "paid" } }

2. Group stage

$group buckets documents by _id and runs accumulators over each bucket.

{ $group: { _id: "$customerId", total: { $sum: "$amount" } } }

3. Grouping key

The _id of $group is the key to group by; here every order with the same customerId collapses into one result.

_id: "$customerId"

4. Accumulator

$sum adds the field across the group; $avg, $min, $max, and $count work the same way.

total: { $sum: "$amount" }

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

$match & $group: Lesson & Practice · Typorithm | ApplyDjinn