Aggregation Fundamentals
$project
Reshape documents in the pipeline: include, exclude, and compute fields.
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"] }
}
}
]){ name: "Mechanical Keyboard", price: 4500, inventoryValue: 90000 }db.users.aggregate([
{ $group: { _id: "$city", totalUsers: { $sum: 1 } } },
{ $project: { _id: 0, city: "$_id", totalUsers: 1 } }
])$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?
Both include and exclude fields. Pipeline $project can also compute fields with expressions. A $project that only lists new fields drops the old ones; use $set when you want to add a field and keep the rest.
Practice