MongoDB Aggregation Pipelines

MongoDB Tutorial

MongoDB Aggregation Pipelines 🔥

In MongoDB, the Aggregation Pipeline is a powerful framework used to process, transform, and analyze data.

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

OperatorPurpose
$sumTotal
$avgAverage
$minMinimum
$maxMaximum
$firstFirst value
$lastLast 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 $match as early as possible

  • Use indexes with $match

  • Avoid large $lookup without indexes

  • Test pipelines in MongoDB Compass


Quick Recap 🧠


 

You may also like...