Bird
Raised Fist0
MongoDBquery~20 mins

$addFields for computed fields in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MongoDB $addFields Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
What is the output of this $addFields stage?
Given a collection with documents like {"name": "Alice", "scores": [10, 20, 30]}, what will be the result of this aggregation pipeline stage?
{ "$addFields": { "totalScore": { "$sum": "$scores" } }}
MongoDB
db.collection.aggregate([{ "$addFields": { "totalScore": { "$sum": "$scores" } }}])
A[{"name": "Alice", "scores": [10, 20, 30], "totalScore": 60}]
B[{"name": "Alice", "scores": [10, 20, 30], "totalScore": [10, 20, 30]}]
C[{"name": "Alice", "scores": [10, 20, 30], "totalScore": 3}]
D[{"name": "Alice", "scores": [10, 20, 30], "totalScore": null}]
Attempts:
2 left
💡 Hint
Think about what $sum does when applied to an array field.
❓ query_result
intermediate
2:00remaining
What does this $addFields expression compute?
Consider documents with fields {"price": 100, "tax": 0.15}. What will this $addFields stage add?
{ "$addFields": { "finalPrice": { "$multiply": ["$price", { "$add": [1, "$tax"] }] } }}
MongoDB
db.collection.aggregate([{ "$addFields": { "finalPrice": { "$multiply": ["$price", { "$add": [1, "$tax"] }] } }}])
A[{"price": 100, "tax": 0.15, "finalPrice": 100.15}]
B[{"price": 100, "tax": 0.15, "finalPrice": 15}]
C[{"price": 100, "tax": 0.15, "finalPrice": 1.15}]
D[{"price": 100, "tax": 0.15, "finalPrice": 115}]
Attempts:
2 left
💡 Hint
Calculate 100 * (1 + 0.15).
📝 Syntax
advanced
2:00remaining
Which $addFields syntax is valid to add a field 'discounted' as price minus discount?
Choose the correct $addFields stage to compute 'discounted' = price - discount.
A{ "$addFields": { "discounted": { "$subtract": ["$price", "$discount"] } } }
B{ "$addFields": { "discounted": "$price" - "$discount" } }
C{ "$addFields": { "discounted": { "$minus": ["$price", "$discount"] } } }
D{ "$addFields": { "discounted": { "$subtract": "$price" - "$discount" } } }
Attempts:
2 left
💡 Hint
Use the correct MongoDB operator for subtraction with array syntax.
❓ optimization
advanced
2:00remaining
How to optimize adding multiple computed fields in one $addFields stage?
You want to add 'total' as sum of 'a' and 'b', and 'average' as their average. Which $addFields stage is best?
A{ "$addFields": { "total": { "$add": ["$a", "$b"] } } }, { "$addFields": { "average": { "$divide": [{ "$add": ["$a", "$b"] }, 2] } } }
B[{ "$addFields": { "total": { "$add": ["$a", "$b"] } } }, { "$addFields": { "average": { "$divide": [{ "$add": ["$a", "$b"] }, 2] } } }]
C{ "$addFields": { "total": { "$add": ["$a", "$b"] }, "average": { "$divide": [{ "$add": ["$a", "$b"] }, 2] } } }
D{ "$addFields": { "average": { "$divide": [{ "$add": ["$a", "$b"] }, 2] } }, { "$addFields": { "total": { "$add": ["$a", "$b"] } } } }
Attempts:
2 left
💡 Hint
Combine all computed fields in a single $addFields stage for efficiency.
🧠 Conceptual
expert
2:00remaining
What happens if $addFields uses a field name that already exists?
If a document has a field 'status' and you use $addFields to add 'status' with a new value, what is the result?
AMongoDB throws an error because field names must be unique.
BThe existing 'status' field is replaced with the new value from $addFields.
CThe new 'status' field is added alongside the existing one as an array.
DThe existing 'status' field is kept and the new one is ignored.
Attempts:
2 left
💡 Hint
Think about how $addFields modifies documents in aggregation.

Practice

(1/5)
1. What is the primary purpose of the $addFields stage in a MongoDB aggregation pipeline?
easy
A. To add new fields or update existing fields with computed values in documents
B. To delete fields from documents permanently
C. To sort documents based on a field
D. To group documents by a specific field

Solution

  1. Step 1: Understand the role of $addFields

    $addFields is used to add new fields or update existing fields with computed values inside documents during aggregation.
  2. Step 2: Compare with other stages

    Deleting fields is done by $project, sorting by $sort, and grouping by $group. These are different from $addFields.
  3. Final Answer:

    To add new fields or update existing fields with computed values in documents -> Option A
  4. Quick Check:

    $addFields adds or updates fields [OK]
Hint: Remember: $addFields enriches documents with new computed fields [OK]
Common Mistakes:
  • Confusing $addFields with $project which removes fields
  • Thinking $addFields sorts or groups documents
  • Assuming $addFields deletes fields
2. Which of the following is the correct syntax to add a new field named totalPrice that multiplies price and quantity using $addFields?
easy
A. { $addFields: { totalPrice: "$price" * "$quantity" } }
B. { $addFields: { totalPrice: "$price" + "$quantity" } }
C. { $addFields: { totalPrice: { $multiply: ["$price", "$quantity"] } } }
D. { $addFields: { totalPrice: { $add: ["$price", "$quantity"] } } }

Solution

  1. Step 1: Identify correct operator for multiplication

    MongoDB uses $multiply with an array of fields to multiply values.
  2. Step 2: Check syntax correctness

    { $addFields: { totalPrice: { $multiply: ["$price", "$quantity"] } } } correctly uses $multiply with array syntax and field references with $.
  3. Final Answer:

    { $addFields: { totalPrice: { $multiply: ["$price", "$quantity"] } } } -> Option C
  4. Quick Check:

    Use $multiply with array for multiplication [OK]
Hint: Use $multiply with array of fields for multiplication [OK]
Common Mistakes:
  • Using arithmetic operators like * directly inside $addFields
  • Confusing $add with multiplication
  • Missing $ before field names
3. Given the collection documents:
{ "item": "apple", "price": 2, "quantity": 5 }

What will be the output document after applying this aggregation stage?
{ $addFields: { totalCost: { $multiply: ["$price", "$quantity"] } } }
medium
A. Error: Invalid operator
B. { "item": "apple", "price": 2, "quantity": 5, "totalCost": "2*5" }
C. { "item": "apple", "price": 2, "quantity": 5 }
D. { "item": "apple", "price": 2, "quantity": 5, "totalCost": 10 }

Solution

  1. Step 1: Calculate the multiplication of price and quantity

    2 multiplied by 5 equals 10.
  2. Step 2: Understand $addFields adds the computed field

    The new field totalCost will be added with value 10.
  3. Final Answer:

    { "item": "apple", "price": 2, "quantity": 5, "totalCost": 10 } -> Option D
  4. Quick Check:

    2 * 5 = 10 added as totalCost [OK]
Hint: Multiply fields inside $addFields to get computed values [OK]
Common Mistakes:
  • Expecting string expression instead of computed number
  • Forgetting to add the new field in output
  • Assuming syntax error when operator is correct
4. Identify the error in this aggregation stage:
{ $addFields: { discountPrice: { $multiply: "$price", 0.9 } } }
medium
A. Cannot multiply a field by a number in $addFields
B. Incorrect use of $multiply operator syntax; expects an array
C. Field name discountPrice is invalid
D. Missing $ before price

Solution

  1. Step 1: Check $multiply syntax

    $multiply requires an array of expressions, but here it is given two separate arguments.
  2. Step 2: Identify correct syntax

    The correct syntax is { $multiply: ["$price", 0.9] } using an array.
  3. Final Answer:

    Incorrect use of $multiply operator syntax; expects an array -> Option B
  4. Quick Check:

    $multiply needs array of operands [OK]
Hint: Always use array syntax with $multiply [OK]
Common Mistakes:
  • Passing arguments to $multiply without array brackets
  • Assuming field names cannot be multiplied by numbers
  • Confusing field name syntax with missing $
5. You have documents with fields price and taxRate. You want to add a field finalPrice that is price plus price multiplied by taxRate. Which $addFields stage correctly computes this?
hard
A. { $addFields: { finalPrice: { $add: ["$price", { $multiply: ["$price", "$taxRate"] }] } } }
B. { $addFields: { finalPrice: "$price" + "$price" * "$taxRate" } }
C. { $addFields: { finalPrice: { $multiply: ["$price", "$taxRate"] } } }
D. { $addFields: { finalPrice: { $add: ["$price", "$taxRate"] } } }

Solution

  1. Step 1: Understand the formula for finalPrice

    The formula is price + (price * taxRate), which requires addition and multiplication.
  2. Step 2: Check correct MongoDB operators usage

    { $addFields: { finalPrice: { $add: ["$price", { $multiply: ["$price", "$taxRate"] }] } } } uses $add with an array containing price and the multiplication result of price and taxRate, which is correct syntax.
  3. Final Answer:

    { $addFields: { finalPrice: { $add: ["$price", { $multiply: ["$price", "$taxRate"] }] } } } -> Option A
  4. Quick Check:

    Use nested $add and $multiply for combined calculations [OK]
Hint: Nest $multiply inside $add for combined calculations [OK]
Common Mistakes:
  • Trying to use arithmetic operators directly inside $addFields
  • Adding price and taxRate directly without multiplication
  • Using wrong operator or missing array brackets
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard