Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to MongoDB
MongoDB Aggregation Pipeline Explained

MongoDB Aggregation Pipeline Explained

MongoDB1,102 viewsBy Admin
mongodbaggregationpipeline

Advertisement

What is the Aggregation Pipeline?

Aggregation processes documents through a series of stages — filtering, grouping, transforming — to compute results like totals and averages. Think of it as MongoDB's version of SQL GROUP BY but far more powerful.

A Simple Pipeline

db.orders.aggregate([
  { $match: { status: "completed" } },     // filter
  { $group: {
      _id: "$customerId",
      total: { $sum: "$amount" }            // sum per customer
  }},
  { $sort: { total: -1 } }                  // highest first
]);

Common Stages

StageDoes
$matchFilter documents
$groupGroup & aggregate
$sortOrder results
$projectReshape fields
$lookupJoin collections

Joining with $lookup

db.orders.aggregate([
  { $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "user"
  }}
]);

FAQs

When use aggregation vs find?

Use find for simple queries; aggregation for grouping, joins, and computed results. More in our MongoDB guides.

Is aggregation fast?

Yes, especially with indexes on $match fields placed early.

Advertisement