MongoDB Aggregation Pipelines

MongoDB Aggregation Pipelines 🔥
It works like a data processing pipeline, where documents pass through multiple stages, and each stage transforms the data.
What is an Aggregation Pipeline?
A sequence of stages
Each stage starts with
$Output of one stage becomes input of the next
Used for reporting, analytics, grouping, filtering
Basic Syntax
1️⃣ $match – Filter Documents (Like WHERE)
📌 Filters documents early → better performance
2️⃣ $project – Select / Transform Fields
You can also create new fields:
3️⃣ $group – Group & Aggregate Data (Most Important)
Common Accumulators
| Operator | Purpose |
|---|---|
$sum | Total |
$avg | Average |
$min | Minimum |
$max | Maximum |
$first | First value |
$last | Last value |
4️⃣ $sort – Sort Documents
5️⃣ $limit & $skip
6️⃣ $unwind – Deconstruct Array Field
Before
Pipeline
After
7️⃣ $lookup – Join Collections (Like SQL JOIN)
📌 MongoDB-style JOIN 🔥
8️⃣ $count – Count Documents
9️⃣ $addFields – Add New Fields
🔟 $facet – Multiple Pipelines at Once (Advanced)
Real-Life Example 🧠
👉 Find total students per course, average age > 20
SQL vs MongoDB Aggregation
SQL
MongoDB
Best Practices ⚠️
Use
$matchas early as possibleUse indexes with
$matchAvoid large
$lookupwithout indexesTest pipelines in MongoDB Compass
