# An Aggregation Example — MongoDB

Source: https://www.geekswithgeeks.com/en/mongodb/mongo-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.

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

**Quiz:** What does the $group stage do?

- [ ] Filters out unwanted documents
- [x] 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.
