MongoDB Aggregation $addFields
Introduction
The $addFields
stage in MongoDB's aggregation framework is used to add new fields to documents or modify existing fields within a pipeline. This stage is useful for transforming your data by calculating new values or altering the structure of your documents before they are passed to subsequent stages in the aggregation pipeline.
Prerequisites
MongoDB installed and running on your machine.
Access to
mongosh
and a populated database with sample data.
Step 1: Start mongosh
mongosh
Open Terminal/Command Prompt:
Launch your terminal (macOS/Linux) or command prompt (Windows).
Start
mongosh
:Type the following command and press Enter:
Step 2: Switch to the Database
Switch to the database where your collection is located.
Use a Database:
Step 3: Sample Data
Let’s assume you have a collection named sales
with documents that look like this:
Step 4: Using $addFields
$addFields
1. Basic Usage of $addFields
$addFields
To add a new field to each document, use the $addFields
stage. For example, if you want to add a totalPrice
field that calculates the total price for each item based on quantity
and price
:
Output:
2. Modifying Existing Fields
You can also use $addFields
to modify existing fields. For instance, if you want to increase the price of each item by 10%:
Output:
3. Adding Multiple Fields
You can add multiple fields in a single $addFields
stage. For example, to add both totalPrice
and a new field called status
based on the quantity:
Output:
4. Combining $addFields
with Other Stages
$addFields
with Other StagesYou can combine $addFields
with other aggregation stages for more complex data transformations. For example, you can first filter items that are in stock and then add the totalPrice
:
Output:
Conclusion
You have learned how to use the $addFields
stage in MongoDB's aggregation framework to add or modify fields in documents. This stage is essential for transforming your data, allowing you to perform calculations and create a more informative dataset for analysis and reporting.
Feel free to reach out if you have any questions or need further guidance!
Last updated