Challenge - 5 Problems
MongoDB $sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Calculate total sales per product
Given a collection sales with documents containing
product and amount, what is the output of this aggregation pipeline?MongoDB
db.sales.aggregate([
{ $group: { _id: "$product", totalSales: { $sum: "$amount" } } }
])Attempts:
2 left
💡 Hint
Sum the amounts grouped by product name.
✗ Incorrect
The $sum accumulator adds all the amounts for each product. The output shows total sales per product.
🧠 Conceptual
intermediate1:30remaining
Understanding $sum with constant values
What does the following aggregation pipeline output if applied to any collection?
MongoDB
db.collection.aggregate([
{ $group: { _id: null, count: { $sum: 1 } } }
])Attempts:
2 left
💡 Hint
Think about what summing 1 for each document means.
✗ Incorrect
Using $sum: 1 counts the number of documents because it adds 1 for each document.
📝 Syntax
advanced2:00remaining
Identify the syntax error in $sum usage
Which option contains a syntax error in using $sum inside a $group stage?
MongoDB
db.orders.aggregate([
{ $group: { _id: "$customer", total: { $sum: "price" } } }
])Attempts:
2 left
💡 Hint
Field names must be prefixed with $ inside $sum to refer to fields.
✗ Incorrect
The $sum accumulator requires a field path prefixed with $ to sum field values. Using a string without $ causes an error.
❓ optimization
advanced2:30remaining
Optimizing $sum with $match before $group
Which pipeline is more efficient to calculate total sales for products with amount > 100?
Attempts:
2 left
💡 Hint
Filtering early reduces documents processed in grouping.
✗ Incorrect
Applying $match before $group reduces the number of documents to group, improving performance.
🔧 Debug
expert3:00remaining
Why does this $sum aggregation return incorrect totals?
Given this pipeline, why might the total be incorrect?
MongoDB
db.orders.aggregate([
{ $group: { _id: "$customer", total: { $sum: "$items.price" } } }
])Attempts:
2 left
💡 Hint
Think about summing values inside arrays.
✗ Incorrect
To sum values inside an array field, you must unwind the array first to flatten documents.