Problem Statement
What is the purpose of the $project stage in aggregation?
Explanation
The dollar project stage reshapes documents by specifying which fields to include or exclude, renaming fields, or computing new fields using expressions. It is similar to projections in find queries but more powerful.
You can use dollar project to add computed fields, extract nested field values, create new structures, or remove unnecessary fields to reduce document size. Place dollar project after filtering and grouping to transform only the final results.
Code Solution
SolutionRead Only
// Reshape employee documents
db.employees.aggregate([
{
$project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
salary: 1,
department: 1,
_id: 0
}
}
])