MongoDB Aggregation $group

MongoDB Aggregation $group 📊

In MongoDB, the $group stage is the heart of the Aggregation Pipeline.

It groups documents by a key and performs calculations (aggregations) on each group—similar to GROUP BY in SQL.


What does $group do?

  • Combines multiple documents into one document per group

  • Uses accumulator operators like $sum, $avg, $min, $max

  • Requires an _id field (grouping key)


Basic Syntax


📌 _id defines how documents are grouped


1️⃣ Group by a Field (Most Common)

Example: Count students per course


Output

{ _id: "BA", totalStudents: 12 }
{ _id: "BSc", totalStudents: 8 }

2️⃣ Group + Average, Min, Max

Example: Average age per course



3️⃣ Group All Documents Together

Use _id: null


📌 Useful for overall totals


4️⃣ Group with $match (Best Practice 👍)

Example: Count BA students above age 20


$match first = better performance


5️⃣ Group by Multiple Fields

Example: Group by course + gender


6️⃣ $group with $sum on a Field

Example: Total marks per course


7️⃣ $first and $last

📌 Usually combined with $sort


Common $group Accumulators

Operator Purpose
$sum Count or total
$avg Average
$min Minimum
$max Maximum
$first First value
$last Last value
$push Push values into array
$addToSet Push unique values

SQL vs MongoDB $group

SQL

MongoDB


Common Mistakes ⚠️

  • Forgetting _id in $group

  • Using $group before $match

  • Expecting original document fields after grouping


Quick Recap 🧠

You may also like...