$group
$group: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 53 of 100
$group
Foundations & CRUD ✓ → Queries & Schema ✓ → Aggregation & Scale → Atlas & Projects
Aggregation & Scale · 3 — Pipelines · ~10 min · MongoDB — Aggregation Pipelines
What is this?
$group buckets documents by an _id expression and computes accumulators like $sum, $avg, $min, $max, and $push.
Why should you care?
Sales by category, messages per room, and average rating per course all need grouping.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
db.products.insertMany([
{ category: "audio", price: 1000 },
{ category: "audio", price: 3000 },
{ category: "storage", price: 4000 }
])
db.products.aggregate([
{ $group: {
_id: "$category",
avgPrice: { $avg: "$price" },
count: { $sum: 1 },
prices: { $push: "$price" }
}}
])
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- _id: "$category" creates one bucket per category.
- $avg computes mean price.
- $sum: 1 counts docs.
- $push builds an array of prices — useful but can get large.
Practice next
- Run the pipeline and read both buckets.
- Try _id: null to aggregate the whole collection into one row.
- Use $max and $min on price.
- Group orders by { tenantId: "$tenantId", status: "$status" }.
- Replace $push with $addToSet.
Remember
$group creates buckets via _id. Accumulators compute metrics. Keep $push arrays bounded.
Category average price report
Merchandising checks avg selling price per category weekly.
Outcome: $group returns one row per category for the sheet.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!