Skip to content

Aggregation Fundamentals

$project

Reshape documents in the pipeline: include, exclude, and compute fields.

IntermediateAbout 5 minutes

Find's projection keeps or drops fields. Pipeline $project can also compute fields. Inclusion / exclusion rules still apply — including _id: 0. After $group, $project is how you rename _id for an API.

db.products.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      price: 1,
      inventoryValue: { $multiply: ["$price", "$stock"] }
    }
  }
])
Keep some fields, compute one, drop _id
{ name: "Mechanical Keyboard", price: 4500, inventoryValue: 90000 }
db.users.aggregate([
  { $group: { _id: "$city", totalUsers: { $sum: 1 } } },
  { $project: { _id: 0, city: "$_id", totalUsers: 1 } }
])
After a group, reshape for the client

$project with only computed fields still drops everything you did not name (except _id unless you exclude it). If you only wanted to add inventoryValue and keep the rest, that is $set — next lesson. Expressions ($multiply, $concat, $cond) get their own module; you only need 'field paths start with $' here.

Interview question

How is $project in a pipeline different from find's projection?

Think about it first.

Practice