#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
7 min read
Question 6 of 27medium

What is the MongoDB Aggregation Pipeline?

Understanding data aggregation in MongoDB.

What You'll Learn

  • What aggregation is
  • Pipeline stages
  • Common examples

What is Aggregation?

Aggregation processes data records and returns computed results. It's like SQL GROUP BY with more power.

Pipeline Stages

code.jsJavaScript
db.collection.aggregate([
  { $match: { ... } },    // Filter documents
  { $group: { ... } },    // Group and aggregate
  { $sort: { ... } },     // Sort results
  { $project: { ... } },  // Shape output
  { $limit: 10 }          // Limit results
]);

Common Stages

$match - Filter

code.jsJavaScript
{ $match: { status: "active", age: { $gte: 18 } } }

$group - Aggregate

code.jsJavaScript
{
  $group: {
    _id: "$department",
    totalSalary: { $sum: "$salary" },
    avgSalary: { $avg: "$salary" },
    count: { $sum: 1 }
  }
}

$project - Shape Output

code.jsJavaScript
{
  $project: {
    name: 1,
    email: 1,
    fullName: { $concat: ["$firstName", " ", "$lastName"] }
  }
}

$sort and $limit

code.jsJavaScript
{ $sort: { totalSales: -1 } },
{ $limit: 10 }

Full Example

code.jsJavaScript
// Get top 5 departments by average salary
db.employees.aggregate([
  { $match: { status: "active" } },
  { $group: {
      _id: "$department",
      avgSalary: { $avg: "$salary" },
      count: { $sum: 1 }
  }},
  { $sort: { avgSalary: -1 } },
  { $limit: 5 },
  { $project: {
      department: "$_id",
      avgSalary: { $round: ["$avgSalary", 2] },
      employeeCount: "$count"
  }}
]);