Example 1 — Sample Data
Four order lines with region and amount. We load them into a collection named orders for grouping and $out demos.
db.orders.drop()
db.orders.insertMany([
{ _id: 1, region: "east", amount: 50 },
{ _id: 2, region: "east", amount: 70 },
{ _id: 3, region: "north", amount: 40 },
{ _id: 4, region: "west", amount: 25 }
]) How the Data Is Stored in MongoDB
After the insert, MongoDB keeps four documents in orders. Run find() to see them:
db.orders.find() Each order line uses these fields:
| Field in MongoDB | Example | Plain English |
|---|---|---|
_id | 1 | Document id for this lesson |
region | "east" | Sales region to group by |
amount | 50 | Line amount to sum in $group |
orders (raw lines):
_id region amount
--- ------ ------
1 east 50
2 east 70 → east total 120
3 north 40
4 west 25
Examples 2–4 group these rows and $out the snapshot. How It Works
- Reset once.
drop()clears old rows;insertManyloads four order lines. - Two fields matter.
regionis the group key;amountis summed. - find() confirms storage. You see the same rows the pipeline reads.
- Reuse. Examples 2–4 assume this data is already in
orders.

