Lesson 14 / 22

An Aggregation Example

Match, group and sort orders into a category summary.

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
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.