Reshape Output Fields with Aggregation
For more advanced transformations, such as renaming fields or creating new computed fields, the find() method's projection is not enough. Instead, you can use the aggregation framework, specifically the $project stage.
Let's prepare our data for this step. Clear the collection and insert users with salary information.
db.users.deleteMany({});
db.users.insertMany([
{
name: "John Doe",
age: 30,
salary: 75000,
department: "Engineering"
},
{
name: "Jane Smith",
age: 28,
salary: 85000,
department: "Data Science"
},
{
name: "Mike Johnson",
age: 35,
salary: 95000,
department: "Management"
}
]);
The $project stage in an aggregation pipeline can reshape documents by adding new fields, renaming existing fields, or removing fields. To use it, you pass an array of stages to the aggregate() method.
To rename a field, you define a new field name and assign it the value of an existing field, prefixed with a $ sign. Let's rename name to fullName and age to yearsOld.
db.users.aggregate([
{
$project: {
fullName: "$name",
yearsOld: "$age",
_id: 0
}
}
]);
You can also create new fields based on calculations. Let's create a monthlySalary field by dividing the annual salary by 12, and a salaryTier field based on conditional logic using the $switch operator.
db.users.aggregate([
{
$project: {
name: 1,
monthlySalary: { $divide: ["$salary", 12] },
salaryTier: {
$switch: {
branches: [
{ case: { $lt: ["$salary", 80000] }, then: "Junior" },
{ case: { $gte: ["$salary", 80000] }, then: "Senior" }
],
default: "Unknown"
}
},
_id: 0
}
}
]);
The output will be a completely new document structure that you defined in the $project stage:
[
{ "name": "John Doe", "monthlySalary": 6250, "salaryTier": "Junior" },
{
"name": "Jane Smith",
"monthlySalary": 7083.333333333333,
"salaryTier": "Senior"
},
{
"name": "Mike Johnson",
"monthlySalary": 7916.666666666667,
"salaryTier": "Senior"
}
]
The $project stage gives you complete control over the final shape of your query results, enabling powerful data transformations directly within the database.