Welcome to TheCodingCollege.com, your reliable resource for coding and programming tutorials. In this article, we’ll explore the $addFields
stage in MongoDB’s aggregation pipeline, which allows you to add or modify fields in your documents dynamically.
What is $addFields
?
The $addFields
stage is used in MongoDB’s aggregation pipeline to create new fields or overwrite existing fields in documents. This is especially useful for dynamically generating additional data fields based on existing values.
Unlike traditional updates, $addFields
is used within the pipeline, meaning it doesn’t permanently modify the source documents but works on the pipeline’s processed output.
Syntax of $addFields
{ $addFields: { <newField>: <expression>, ... } }
<newField>
: The name of the new or modified field.<expression>
: A valid aggregation expression to define the field’s value.
Example 1: Adding a New Field
Suppose you have a sales
collection:
[
{ "item": "Laptop", "price": 1000, "quantity": 2 },
{ "item": "Phone", "price": 500, "quantity": 5 }
]
Task: Add a new field totalRevenue
(price × quantity).
db.sales.aggregate([
{
$addFields: {
totalRevenue: { $multiply: ["$price", "$quantity"] }
}
}
])
Output:
[
{ "item": "Laptop", "price": 1000, "quantity": 2, "totalRevenue": 2000 },
{ "item": "Phone", "price": 500, "quantity": 5, "totalRevenue": 2500 }
]
Example 2: Modifying an Existing Field
You can overwrite an existing field by using the same field name.
Task: Adjust the price
field by adding a 10% tax.
db.sales.aggregate([
{
$addFields: {
price: { $multiply: ["$price", 1.1] }
}
}
])
Output:
[
{ "item": "Laptop", "price": 1100, "quantity": 2 },
{ "item": "Phone", "price": 550, "quantity": 5 }
]
Example 3: Adding Multiple Fields
Task: Add discountedPrice
(10% off) and profitMargin
(20% of price).
db.sales.aggregate([
{
$addFields: {
discountedPrice: { $multiply: ["$price", 0.9] },
profitMargin: { $multiply: ["$price", 0.2] }
}
}
])
Output:
[
{
"item": "Laptop",
"price": 1000,
"quantity": 2,
"discountedPrice": 900,
"profitMargin": 200
},
{
"item": "Phone",
"price": 500,
"quantity": 5,
"discountedPrice": 450,
"profitMargin": 100
}
]
Real-World Use Cases for $addFields
- E-commerce: Calculate total revenue, discounts, or taxes on products.
- Financial Analysis: Generate derived metrics such as profit margins or growth rates.
- Data Cleaning: Add fields based on conditional logic for data normalization.
Best Practices for Using $addFields
- Efficient Usage: Use
$addFields
sparingly to avoid overloading the pipeline with excessive calculations. - Combine with
$project
: To streamline the output, combine$addFields
with$project
to display only relevant fields. - Indexing: For frequently used computed fields, consider adding them to the original dataset instead of calculating dynamically.
Real-World Application
Task: Add a status
field to a tasks
collection to categorize tasks as Completed
or Pending
.
db.tasks.aggregate([
{
$addFields: {
status: {
$cond: { if: { $eq: ["$completed", true] }, then: "Completed", else: "Pending" }
}
}
}
])
This approach makes it easy to classify and manage tasks dynamically.
Conclusion
The $addFields
stage in MongoDB’s aggregation pipeline is an incredibly versatile tool for enhancing your data on the fly. Whether you’re adding calculated fields or modifying existing ones, it helps streamline data analysis and reporting tasks.