$addFields lets you add new fields or change existing ones in your data by calculating values. It helps you create extra information without changing the original data.
$addFields for computed fields in MongoDB
db.collection.aggregate([
{
$addFields: {
newField1: <expression>,
newField2: <expression>
}
}
])The $addFields stage is used inside an aggregation pipeline.
You can add multiple fields at once by listing them inside the $addFields object.
totalPrice by multiplying quantity and price.db.orders.aggregate([
{
$addFields: {
totalPrice: { $multiply: ["$quantity", "$price"] }
}
}
])fullName field by joining first and last names with a space.db.users.aggregate([
{
$addFields: {
fullName: { $concat: ["$firstName", " ", "$lastName"] }
}
}
])isAdult field that is true if age is 18 or more.db.people.aggregate([
{
$addFields: {
isAdult: { $gte: ["$age", 18] }
}
}
])This query adds two new fields: totalCost which is units sold times unit price, and discountPrice which applies a 10% discount to the unit price before multiplying by units sold.
db.sales.aggregate([
{
$addFields: {
totalCost: { $multiply: ["$unitsSold", "$unitPrice"] },
discountPrice: { $multiply: ["$unitsSold", { $multiply: ["$unitPrice", 0.9] }] }
}
}
])If the field already exists, $addFields will overwrite it with the new value.
You can use any valid MongoDB expression inside $addFields to compute values.
$addFields adds or updates fields with computed values in documents.
It is used inside aggregation pipelines to enrich data without changing the original collection.
You can add multiple computed fields at once using $addFields.
Practice
$addFields stage in a MongoDB aggregation pipeline?Solution
Step 1: Understand the role of
$addFields$addFieldsis used to add new fields or update existing fields with computed values inside documents during aggregation.Step 2: Compare with other stages
Deleting fields is done by$project, sorting by$sort, and grouping by$group. These are different from$addFields.Final Answer:
To add new fields or update existing fields with computed values in documents -> Option AQuick Check:
$addFieldsadds or updates fields [OK]
$addFields enriches documents with new computed fields [OK]- Confusing
$addFieldswith$projectwhich removes fields - Thinking
$addFieldssorts or groups documents - Assuming
$addFieldsdeletes fields
totalPrice that multiplies price and quantity using $addFields?Solution
Step 1: Identify correct operator for multiplication
MongoDB uses$multiplywith an array of fields to multiply values.Step 2: Check syntax correctness
{ $addFields: { totalPrice: { $multiply: ["$price", "$quantity"] } } } correctly uses$multiplywith array syntax and field references with$.Final Answer:
{ $addFields: { totalPrice: { $multiply: ["$price", "$quantity"] } } } -> Option CQuick Check:
Use$multiplywith array for multiplication [OK]
$multiply with array of fields for multiplication [OK]- Using arithmetic operators like * directly inside
$addFields - Confusing
$addwith multiplication - Missing
$before field names
{ "item": "apple", "price": 2, "quantity": 5 }What will be the output document after applying this aggregation stage?
{ $addFields: { totalCost: { $multiply: ["$price", "$quantity"] } } }Solution
Step 1: Calculate the multiplication of
2 multiplied by 5 equals 10.priceandquantityStep 2: Understand
The new field$addFieldsadds the computed fieldtotalCostwill be added with value 10.Final Answer:
{ "item": "apple", "price": 2, "quantity": 5, "totalCost": 10 } -> Option DQuick Check:
2 * 5 = 10 added astotalCost[OK]
$addFields to get computed values [OK]- Expecting string expression instead of computed number
- Forgetting to add the new field in output
- Assuming syntax error when operator is correct
{ $addFields: { discountPrice: { $multiply: "$price", 0.9 } } }Solution
Step 1: Check
$multiplysyntax$multiplyrequires an array of expressions, but here it is given two separate arguments.Step 2: Identify correct syntax
The correct syntax is{ $multiply: ["$price", 0.9] }using an array.Final Answer:
Incorrect use of$multiplyoperator syntax; expects an array -> Option BQuick Check:
$multiplyneeds array of operands [OK]
$multiply [OK]- Passing arguments to
$multiplywithout array brackets - Assuming field names cannot be multiplied by numbers
- Confusing field name syntax with missing
$
price and taxRate. You want to add a field finalPrice that is price plus price multiplied by taxRate. Which $addFields stage correctly computes this?Solution
Step 1: Understand the formula for
The formula isfinalPriceprice + (price * taxRate), which requires addition and multiplication.Step 2: Check correct MongoDB operators usage
{ $addFields: { finalPrice: { $add: ["$price", { $multiply: ["$price", "$taxRate"] }] } } } uses$addwith an array containingpriceand the multiplication result ofpriceandtaxRate, which is correct syntax.Final Answer:
{ $addFields: { finalPrice: { $add: ["$price", { $multiply: ["$price", "$taxRate"] }] } } } -> Option AQuick Check:
Use nested$addand$multiplyfor combined calculations [OK]
$multiply inside $add for combined calculations [OK]- Trying to use arithmetic operators directly inside
$addFields - Adding
priceandtaxRatedirectly without multiplication - Using wrong operator or missing array brackets
Ready to prove it?
Pass the test and this pattern moves unknown
