MongoDB Aggregation Pipeline

Group, filter and transform data in stages.

✍️ 2 exercises in this lesson

The aggregation pipeline passes documents through stages, like an assembly line:

  • $match: filter (like WHERE).
  • $group: group and calculate (like GROUP BY), with $sum, $avg, $max…
  • $sort, $limit, $project, $lookup (join another collection).

Key Takeaways: MongoDB Aggregation Pipeline

Mastering MongoDB Aggregation Pipeline helps you write clean and reliable MongoDB code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

MongoDB Aggregation Pipeline Code Example

MongoDB
db.students.aggregate([
  { $match: { marks: { $gte: 60 } } },
  { $group: { _id: "$city", students: { $sum: 1 }, avgMarks: { $avg: "$marks" } } },
  { $sort: { avgMarks: -1 } }
])
Output
[
  { _id: 'Karachi', students: 1, avgMarks: 94 },
  { _id: 'Lahore', students: 1, avgMarks: 81 },
  { _id: 'Rawalpindi', students: 1, avgMarks: 72 }
]
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

MongoDB Aggregation Pipeline Practice Exercises

Check what you learned in “MongoDB Aggregation Pipeline”.

/ 2 solved
Fill in the blank

The stage that filters documents (like WHERE).

db.orders.aggregate([ { : { status: "paid" } } ])
✓ Correct! Not quite. Try again.
Multiple choice

Which stage groups documents and calculates totals?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services