Chapter 13: MongoDB Aggregation $group

1. What does $group actually do? (Simple teacher explanation)

$group collects documents that have the same value(s) in one or more fields (the grouping key), and then lets you calculate something about each group.

Think of it like:

  • SQL: GROUP BY city + COUNT(*) + AVG(salary) + SUM(revenue)
  • Excel: Pivot Table
  • Real life: “Group all Valentine’s wishes by who sent them, then count how many each person sent and find the average rating per sender”

Core idea in one sentence:

$group partitions the documents into buckets (groups) based on the _id expression you give it, and then computes accumulators (sum, avg, count, min, max, push, etc.) inside each bucket.

2. Basic Syntax Pattern (Write this in your notebook!)

JavaScript
  • _id is required — this becomes the group identifier
  • You can name the output fields anything you want (they become fields in the result documents)
  • Accumulators almost always start with $ (except a few special cases)

3. Most Important Accumulators (The Tools Inside $group)

Accumulator What it computes Input type Typical output example Very common use case
$sum Sum of values number total revenue revenue, likes, points, quantity
$avg Average (arithmetic mean) number average rating scores, prices, response time
$min / $max Smallest / largest value number, date, string earliest join date, highest score min/max price, date ranges
$first / $last First / last value per group (in sort order) any most recent comment latest entry per group
$push Build array of all values any list of product IDs collect all items, tags, users
$addToSet Build array of unique values any unique categories distinct values per group
$count Count documents in group (MongoDB 5.0+) number of orders cleaner than $sum: 1
$stdDevPop / $stdDevSamp Population / sample standard deviation number rating variability statistics, quality control

4. Hands-on Examples – Let’s Build Real Pipelines

Use the same movieAnalytics2026 database from last class:

JavaScript

Example 1: Simplest — Count movies per year

JavaScript

Result might look like:

JSON

Example 2: Real business case — Revenue & average rating per country

JavaScript

Example 3: Group by multiple fields (composite key)

JavaScript

→ Groups like {India, Action}, {USA, Drama}, etc.

Example 4: Collect unique values + count per sender (Valentine style)

JavaScript

5. Quick Cheat Sheet Table – Your $group Reference Card

Goal _id expression Useful accumulators Typical preceding stage
Count per category “$category” $sum: 1 or $count: {} $match
Total & average per group “$region” $sum: “$amount”, $avg: “$score” $match
Collect all items “$userId” $push: “$productId” $unwind if array
Collect distinct items “$department” $addToSet: “$employeeId”
Get latest document per group “$sensorId” $max: “$timestamp”, $last: “$$ROOT” $sort before group
Group by year-month (date) { $dateToString: { format: “%Y-%m”, date: “$createdAt” } }

6. Mini Exercise – Try These Right Now!

  1. Count how many movies per genre (remember $unwind first)
  2. Find total revenue and movie count per year
  3. For each country, collect the list of movie titles (use $push or $addToSet)
  4. Find the average rating per country — round to 2 decimals

Understood beta? $group is the heart of analytics in MongoDB — once you get comfortable with it, you can answer almost any “how many”, “average”, “total per …” question directly in the database.

Next class options:

  • How to get top N per group (with $sort + $group tricks)?
  • $lookup + $group together (join then summarize)?
  • Date grouping patterns (by day/week/month)?
  • Or a small dashboard-style project?

Tell me what you want next — class is yours! 🚀❤️

Any part of $group confusing? Ask freely — we’ll practice more examples together 😄

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *