← Back to MongoDB Course | Chapter 7: Aggregation | Lesson 1 of 7

Aggregation pipeline

An aggregation pipeline passes documents through a series of stages, each transforming the data.

In this page:

  1. Aggregation pipeline
Syntax
javascript
db.collection_name.aggregate([
  { $match: filter },
  { $group: { _id: "$field", total: { $sum: 1 } } },
  { $sort: { total: -1 } }
])

Aggregation pipeline

db.collection.aggregate([stage1, stage2, ...]) sends documents through stages such as $match, $group, $project and $sort. The output of each stage feeds the next.

Putting $match early reduces the data every later stage must process and lets indexes help.

Note: Filter with $match as early as possible.

Example: Aggregation pipeline

bash
test> db.sales.insertMany([
...   { _id: 1, item: "pen", qty: 5, price: 2 }, { _id: 2, item: "book", qty: 1, price: 12 },
...   { _id: 3, item: "pen", qty: 10, price: 2 }, { _id: 4, item: "lamp", qty: 2, price: 30 }
... ])
{
  acknowledged: true,
  insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.sales.aggregate([
...   { $match: { qty: { $gte: 2 } } },
...   { $project: { _id: 0, item: 1, total: { $multiply: ["$qty", "$price"] } } },
...   { $sort: { total: -1 } }
... ])
[
  { item: 'lamp', total: 60 },
  { item: 'pen', total: 20 },
  { item: 'pen', total: 10 }
]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Passing stages as separate arguments instead of an array
  2. Putting $match after an expensive $group
  3. Forgetting each stage is a separate object
Chapter Summary
  • aggregate takes an array of stages
  • Each stage feeds the next
  • $match early
  • Stages are objects with one operator
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.