Challenge - 5 Problems
MongoDB $addFields Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2: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" } }}])Attempts:
2 left
💡 Hint
Think about what $sum does when applied to an array field.
✗ Incorrect
The $sum operator sums all numbers in the array 'scores', so 10 + 20 + 30 = 60. The $addFields stage adds this as a new field 'totalScore'.
❓ query_result
intermediate2: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"] }] } }}])Attempts:
2 left
💡 Hint
Calculate 100 * (1 + 0.15).
✗ Incorrect
The expression calculates finalPrice as price multiplied by (1 + tax), so 100 * 1.15 = 115.
📝 Syntax
advanced2: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.
Attempts:
2 left
💡 Hint
Use the correct MongoDB operator for subtraction with array syntax.
✗ Incorrect
The $subtract operator requires an array of two expressions to subtract. Option A uses correct syntax.
❓ optimization
advanced2: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?
Attempts:
2 left
💡 Hint
Combine all computed fields in a single $addFields stage for efficiency.
✗ Incorrect
Option C adds both fields in one stage, reducing pipeline stages and improving performance.
🧠 Conceptual
expert2: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?
Attempts:
2 left
💡 Hint
Think about how $addFields modifies documents in aggregation.
✗ Incorrect
$addFields overwrites existing fields if the same name is used, replacing old values with new ones.