In this step, you'll learn how to format and transform output fields using MongoDB's projection and aggregation techniques. We'll explore ways to rename, calculate, and modify fields during projection.
First, let's update our users collection with more detailed information:
// Clear existing documents
db.users.deleteMany({});
// Insert documents with more complex data
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"
}
]);
Use the $
operator to rename fields during projection:
db.users.find(
{},
{
fullName: "$name",
yearsOld: "$age",
annualSalary: "$salary",
_id: 0
}
);
Example output:
[
{ fullName: 'John Doe', yearsOld: 30, annualSalary: 75000 },
{ fullName: 'Jane Smith', yearsOld: 28, annualSalary: 85000 },
{ fullName: 'Mike Johnson', yearsOld: 35, annualSalary: 95000 }
]
You can also perform calculations using the $
aggregation operators:
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
}
}
]);
Example output:
[
{
name: 'John Doe',
monthlySalary: 6250,
salaryTier: 'Junior'
},
{
name: 'Jane Smith',
monthlySalary: 7083.333333333333,
salaryTier: 'Senior'
},
{
name: 'Mike Johnson',
monthlySalary: 7916.666666666667,
salaryTier: 'Senior'
}
]
Key points about formatting output fields:
- Use
$
to rename fields during projection
- Aggregation pipeline allows complex field transformations
- You can perform calculations and create conditional fields
$project
stage is powerful for field formatting