</>
Skip to content
MongoDB lessons (22/38)

MongoDB — Aggregation Pipeline

Pipeline Concept

Documents pass through stages sequentially.

Common Stages

$match

{ $match: { status: "active" } }

$group

{ $group: { _id: "$category", total: { $sum: "$amount" } } }

$sort

{ $sort: { total: -1 } }

$project

{ $project: { name: 1, email: 1, _id: 0 } }

$limit and $skip

{ $skip: 10 }
{ $limit: 5 }

$unwind

{ $unwind: "$hobbies" }

Accumulators

AccumulatorDescription
$sumSum values
$avgAverage
$minMinimum
$maxMaximum
$firstFirst element
$lastLast element

Example Pipeline

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $unwind: "$items" },
  { $group: { 
    _id: "$userId", 
    totalSpent: { $sum: "$items.price" } 
  }},
  { $sort: { totalSpent: -1 } },
  { $limit: 10 }
]);

Mini Practice

  1. Build a pipeline
  2. Use multiple stages
  3. Calculate aggregates
  4. Unwind arrays

Up Next

Continue with Group — grouping documents.

Related Topics

Frequently Asked Questions about Aggregation Pipeline

What is Aggregation Pipeline in MongoDB?

Aggregation Pipeline is a fundamental concept in MongoDB. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Aggregation Pipeline?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Aggregation Pipeline.

Why is Aggregation Pipeline important in MongoDB?

Aggregation Pipeline is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.