Lesson 14 / 23

An Aggregation Example

Build a real pipeline that filters completed orders, groups them by category and sorts totals.

Total sales per category

Filter completed orders, group them by category summing the amount, then sort highest first.

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$category", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } }
])

Output:

[
  { _id: "electronics", total: 48500 },
  { _id: "books", total: 9200 }
]

Reading the pipeline

_id inside $group is the grouping key — here each output document represents one category with its summed amount.

Quick check: What does the $group stage do?

  • Filters out unwanted documents
  • Aggregates documents by a key, computing values like sums
  • Sorts documents in ascending order
  • Creates an index on a field
Answer

Aggregates documents by a key, computing values like sums — $group buckets documents by an _id expression and computes accumulators like $sum, $avg per bucket.