All academies
Roadmap
LEVEL 5 · AGGREGATION FRAMEWORK

$project, $unwind, $lookup

14 min read

$project reshapes documents: include fields, compute new ones, or rename. $addFields is like $project but keeps everything else.

Computed fields
db.products.aggregate([
  { $project: {
      name: 1,
      priceWithTax: { $round: [{ $multiply: ["$price", 1.18] }, 2] },
      _id: 0
  }}
])

$unwind — explode arrays

$unwind outputs one document per array element. A doc with 3 tags becomes 3 docs, each with a single tag — the standard prelude to grouping by array values.

mongosh
db.products.aggregate([
  { $unwind: "$tags" },
  { $sortByCount: "$tags" }   // most common tags
])

$lookup — the JOIN

$lookup performs a left outer join against another collection, putting matches into an array field.

mongosh
db.orders.aggregate([
  { $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "customer"
  }},
  { $unwind: "$customer" },
  { $project: { total: 1, status: 1, "customer.name": 1 } }
])

$facet, $bucket, $count

$facet runs multiple sub-pipelines in one pass (great for dashboards). $bucket groups numeric values into ranges. $count outputs a single doc with the document count. Try them in the visual aggregation builder.

Try it yourself

db.orders.aggregate([{ $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "customer" } }, { $unwind: "$customer" }, { $project: { total: 1, "customer.name": 1 } }])
Run in Shell

Check your understanding

Q1.

A document has tags: ['a','b','c']. After { $unwind: '$tags' }, how many documents come out?

code
{ $unwind: "$tags" }
Q2.

What does $lookup put in the 'as' field when no foreign documents match?

Q3.

Which stage runs several independent sub-pipelines over the same input?