MONGODB Tutorial



MongoDB AGGREGATION


📊 MongoDB Aggregation

Aggregation in MongoDB is a powerful feature used to process and transform data from a collection. It works like SQL’s GROUP BY and allows data to be analyzed and reshaped efficiently using a pipeline of stages.

✅ Basic Syntax

db.collection.aggregate([
  { stage1 },
  { stage2 },
  ...
])
  

🔹 Example: Total Orders per User

db.orders.aggregate([
  { $group: { _id: "$userId", totalOrders: { $sum: 1 } } }
])
  

🔹 Common Aggregation Stages

  • $match → Filters documents (like WHERE in SQL)
  • $group → Groups documents by a field
  • $project → Reshapes the documents (selects fields)
  • $sort → Sorts the result set
  • $limit → Limits number of documents
  • $count → Counts documents

🔹 Example: Filter, Group & Sort

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$userId", totalSpent: { $sum: "$amount" } } },
  { $sort: { totalSpent: -1 } }
])
  
Tip: Aggregation is the best way to perform advanced calculations and reporting directly in MongoDB.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review