TExcelTAD
Home › MongoDB › MongoDB Aggregations

MongoDB Aggregations

find() returns documents as they are stored. When you need something computed (totals per customer, best-selling products, average order value per month), you use the aggregation pipeline.

A pipeline is an array of stages. Documents enter the first stage, each stage transforms the stream of documents, and the output of the last stage is the result:

text
orders ──▶ $match ──▶ $group ──▶ $sort ──▶ $limit ──▶ result
          (filter)  (summarise) (order)   (top N)
js
db.collection.aggregate([ { $stage1: … }, { $stage2: … }, … ])

aggregate() returns a cursor, so in a script you call .toArray() on it, just like with find().

A first pipeline

How much revenue did each order status bring in?

mongosh · try it yourself
const result = db.orders.aggregate([
  { $group: { _id: '$status', orders: { $sum: 1 }, revenue: { $sum: '$total' } } },
  { $sort: { revenue: -1 } }
]).toArray();
print(result);
[
  { _id: 'delivered', orders: 10, revenue: 480 },
  { _id: 'processing', orders: 5, revenue: 360 },
  { _id: 'shipped', orders: 3, revenue: 125.5 },
  { _id: 'cancelled', orders: 2, revenue: 89 }
]

Two ideas appear in every pipeline:

  • Field paths. '$status' and '$total' (a string starting with $) mean "the value of this field in the current document".
  • Stage order matters. Each stage only sees what the previous stage produced. After $group, the documents have the fields _id, orders and revenue, and nothing else, so $sort can sort on revenue.

The most used stages

Stage Does Similar SQL
$match filters documents WHERE / HAVING
$group groups and summarises GROUP BY
$project picks, renames and computes fields SELECT col, expr AS name
$addFields / $set adds computed fields, keeping the rest SELECT *, expr AS name
$sort orders documents ORDER BY
$limit / $skip keeps the first n / skips n LIMIT / OFFSET
$count counts the documents COUNT(*)
$unwind turns each array element into its own document
$lookup joins another collection LEFT OUTER JOIN
$bucket groups numbers into ranges CASE … GROUP BY
$facet runs several sub-pipelines on the same input
$out / $merge writes the result to a collection INSERT INTO … SELECT

Each of them has its own lesson in this section.

Building a pipeline step by step

The best way to write a pipeline is one stage at a time, checking the output after each. Goal: the three best-selling products by units sold, among delivered orders.

Step 1: keep the delivered orders and split them into one document per line item.

mongosh · try it yourself
const step1 = db.orders.aggregate([
  { $match: { status: 'delivered' } },
  { $unwind: '$items' },
  { $limit: 3 }
]).toArray();
print(step1.map(d => [d._id, d.items.name, d.items.qty]));
[
  [ 1001, 'Espresso Beans', 2 ],
  [ 1001, 'Paper Filters (100)', 1 ],
  [ 1002, 'Ethiopia Yirgacheffe', 1 ]
]

Step 2: group the line items by product and add up the quantities, then sort and keep the top three.

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { status: 'delivered' } },
  { $unwind: '$items' },
  { $group: { _id: '$items.name', units: { $sum: '$items.qty' } } },
  { $sort: { units: -1, _id: 1 } },
  { $limit: 3 }
]).toArray());
[
  { _id: 'Dark Chocolate Bar', units: 10 },
  { _id: 'Earl Grey', units: 4 },
  { _id: 'Espresso Beans', units: 3 }
]

Tip: Put $match as early as possible. Fewer documents flow through the later stages, and a $match at the start of a pipeline can use an index.

Expressions

Inside stages like $project, $addFields and $group you can write expressions with operators such as $add, $multiply, $concat, $cond or $dateToString:

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { customerId: 1 } },
  { $project: {
      _id: 0,
      order: '$_id',
      day: { $dateToString: { format: '%Y-%m-%d', date: '$date' } },
      lines: { $size: '$items' },
      totalWithTax: { $round: [{ $multiply: ['$total', 1.2] }, 2] }
  } }
]).toArray());
[
  { order: 1001, day: '2026-03-01', lines: 2, totalWithTax: 66 },
  { order: 1005, day: '2026-03-12', lines: 3, totalWithTax: 70.8 },
  { order: 1013, day: '2026-04-25', lines: 2, totalWithTax: 34.2 }
]

Aggregation doesn't change your data

An aggregation reads documents and returns new ones; the collection itself is untouched, unless the pipeline ends with $out or $merge, which write the result to a collection.

Test yourself

In a pipeline, what does the string '$total' mean?

  1. The text "$total"
  2. The value of the field total in the current document
  3. A variable called total
  4. The sum of all totals

After { $group: { _id: '$status', n: { $sum: 1 } } }, which fields does each output document have?

  1. All the order fields plus n
  2. _id and n
  3. status and n
  4. Only n

Why put $match early in a pipeline?

  1. It is required to be first
  2. Fewer documents reach later stages and it can use an index
  3. $match can only filter original fields
  4. It sorts the documents