$addFields for computed fields in MongoDB - Time & Space Complexity
We want to understand how the time to add new computed fields changes as the data grows.
How does the number of documents affect the work done by $addFields?
Analyze the time complexity of the following code snippet.
db.orders.aggregate([
{
$addFields: {
totalPrice: { $multiply: ["$price", "$quantity"] }
}
}
])
This code adds a new field totalPrice to each order by multiplying price and quantity.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The aggregation processes each document once to compute the new field.
- How many times: Once per document in the collection.
As the number of documents grows, the work grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 computations of totalPrice |
| 100 | 100 computations of totalPrice |
| 1000 | 1000 computations of totalPrice |
Pattern observation: The work increases directly with the number of documents.
Time Complexity: O(n)
This means the time to add computed fields grows linearly with the number of documents.
[X] Wrong: "Adding computed fields with $addFields is instant no matter how many documents there are."
[OK] Correct: Each document must be processed once, so more documents mean more work and more time.
Understanding how operations scale with data size helps you explain your choices clearly and confidently in real projects.
"What if we added multiple computed fields in one $addFields stage? How would the time complexity change?"
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
