Bird
Raised Fist0
MongoDBquery~20 mins

$sum accumulator in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MongoDB $sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2: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" } } }
])
A[{ "_id": "apple", "totalSales": 150 }, { "_id": "banana", "totalSales": 200 }]
B[{ "_id": "apple", "totalSales": 350 }, { "_id": "banana", "totalSales": 200 }]
C[{ "_id": "apple", "totalSales": 150 }, { "_id": "banana", "totalSales": 100 }]
D[{ "_id": "apple", "totalSales": 0 }, { "_id": "banana", "totalSales": 0 }]
Attempts:
2 left
💡 Hint
Sum the amounts grouped by product name.
🧠 Conceptual
intermediate
1: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 } } }
])
A[{ "_id": null, "count": <number_of_documents> }]
B[{ "_id": null, "count": 0 }]
C[{ "_id": null, "count": null }]
DSyntaxError
Attempts:
2 left
💡 Hint
Think about what summing 1 for each document means.
📝 Syntax
advanced
2: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" } } }
])
AUsing $sum: "$price" (with $ before field name) is correct syntax.
BUsing $sum: ["$price"] is correct syntax.
CUsing $sum: { $price: 1 } is correct syntax.
DUsing $sum: "price" (without $) is correct syntax.
Attempts:
2 left
💡 Hint
Field names must be prefixed with $ inside $sum to refer to fields.
❓ optimization
advanced
2:30remaining
Optimizing $sum with $match before $group
Which pipeline is more efficient to calculate total sales for products with amount > 100?
Adb.sales.aggregate([{ $group: { _id: "$product", total: { $sum: "$amount" } } }])
Bdb.sales.aggregate([{ $group: { _id: "$product", total: { $sum: "$amount" } } }, { $match: { total: { $gt: 100 } } }])
Cdb.sales.aggregate([{ $match: { amount: { $gt: 100 } } }, { $group: { _id: "$product", total: { $sum: "$amount" } } }])
Ddb.sales.aggregate([{ $group: { _id: "$product", total: { $sum: { $cond: [{ $gt: ["$amount", 100] }, "$amount", 0] } } } }])
Attempts:
2 left
💡 Hint
Filtering early reduces documents processed in grouping.
🔧 Debug
expert
3: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" } } }
])
ABecause $sum requires numeric literals, not field paths.
BBecause $sum cannot sum values inside arrays without $unwind first.
CBecause $group cannot use nested fields in _id.
DBecause $sum only works with top-level fields, not nested.
Attempts:
2 left
💡 Hint
Think about summing values inside arrays.

Practice

(1/5)
1. What does the $sum accumulator do in a MongoDB aggregation pipeline?
easy
A. Adds values together or counts documents within groups
B. Finds the average value of a field
C. Sorts documents in ascending order
D. Filters documents based on a condition

Solution

  1. Step 1: Understand the role of $sum

    The $sum accumulator adds numeric values or counts documents when used in a $group stage.
  2. Step 2: Compare with other accumulators

    Unlike $avg which calculates averages, $sum only totals values or counts documents.
  3. Final Answer:

    Adds values together or counts documents within groups -> Option A
  4. Quick Check:

    $sum = Adds or counts [OK]
Hint: Remember: $sum totals numbers or counts docs [OK]
Common Mistakes:
  • Confusing $sum with $avg
  • Thinking $sum sorts data
  • Assuming $sum filters documents
2. Which of the following is the correct syntax to sum the field price in a $group stage?
easy
A. { $group: { _id: null, total: { $sum: "price" } } }
B. { $group: { _id: null, total: { $sum: "$price" } } }
C. { $group: { _id: null, total: { $sum: price } } }
D. { $group: { _id: null, total: { sum: "$price" } } }

Solution

  1. Step 1: Identify correct field reference syntax

    In MongoDB aggregation, field names must be prefixed with "$" inside expressions, so "$price" is correct.
  2. Step 2: Check accumulator syntax

    The accumulator must be $sum, not sum, and the value must be a string with "$" prefix.
  3. Final Answer:

    { $group: { _id: null, total: { $sum: "$price" } } } -> Option B
  4. Quick Check:

    Use $sum with "$field" syntax [OK]
Hint: Use "$field" inside $sum in $group [OK]
Common Mistakes:
  • Omitting the $ before field name
  • Using sum instead of $sum
  • Not quoting the field name
3. Given the collection documents:
{ "category": "A", "value": 10 }
{ "category": "A", "value": 20 }
{ "category": "B", "value": 5 }

What will be the output of this aggregation?
[{ $group: { _id: "$category", totalValue: { $sum: "$value" } } }]
medium
A. [{ "_id": "A", "totalValue": 30 }, { "_id": "B", "totalValue": 5 }]
B. [{ "_id": "A", "totalValue": 10 }, { "_id": "B", "totalValue": 5 }]
C. [{ "_id": "A", "totalValue": 20 }, { "_id": "B", "totalValue": 5 }]
D. [{ "_id": null, "totalValue": 35 }]

Solution

  1. Step 1: Group documents by category

    Documents with category "A" are grouped together, and category "B" separately.
  2. Step 2: Sum the "value" fields per group

    For category "A": 10 + 20 = 30; for category "B": 5.
  3. Final Answer:

    [{ "_id": "A", "totalValue": 30 }, { "_id": "B", "totalValue": 5 }] -> Option A
  4. Quick Check:

    Sum values per category [OK]
Hint: Sum values grouped by _id field [OK]
Common Mistakes:
  • Summing without grouping
  • Using null _id causing single group
  • Adding only one document's value
4. Consider this aggregation pipeline:
[{ $group: { _id: "$type", total: { $sum: value } } }]

What is the error in this pipeline?
medium
A. The _id field cannot be a string
B. Missing $group stage
C. Cannot use $sum inside $group
D. Field name 'value' should be quoted and prefixed with $ inside $sum

Solution

  1. Step 1: Check field reference inside $sum

    The field 'value' must be referenced as "$value" (string with $ prefix) inside $sum.
  2. Step 2: Confirm correct $group usage

    The $group stage is present and _id is correctly set to "$type".
  3. Final Answer:

    Field name 'value' should be quoted and prefixed with $ inside $sum -> Option D
  4. Quick Check:

    Use "$field" inside $sum [OK]
Hint: Always quote and prefix field with $ inside $sum [OK]
Common Mistakes:
  • Using unquoted field names inside $sum
  • Thinking $sum can't be used in $group
  • Misunderstanding _id usage
5. You have a collection of sales documents with fields store and amount. You want to find the total sales per store but only for stores with total sales above 1000. Which aggregation pipeline correctly uses $sum and filters the results?
hard
A. [{ $match: { amount: { $gt: 1000 } } }, { $group: { _id: "$store", totalSales: { $sum: "$amount" } } }]
B. [{ $group: { _id: "$store", totalSales: { $sum: "$amount" } } }, { $match: { amount: { $gt: 1000 } } }]
C. [{ $group: { _id: "$store", totalSales: { $sum: "$amount" } } }, { $match: { totalSales: { $gt: 1000 } } }]
D. [{ $group: { _id: "$store", totalSales: { $sum: "$amount" } } }, { $match: { _id: { $gt: 1000 } } }]

Solution

  1. Step 1: Group sales by store and sum amounts

    The first stage groups documents by "store" and sums the "amount" field into "totalSales".
  2. Step 2: Filter groups with totalSales greater than 1000

    The second stage uses $match on the aggregated field "totalSales" to keep only stores with totals above 1000.
  3. Final Answer:

    [{ $group: { _id: "$store", totalSales: { $sum: "$amount" } } }, { $match: { totalSales: { $gt: 1000 } } }] -> Option C
  4. Quick Check:

    Group then filter on sum field [OK]
Hint: Group first, then filter on summed field [OK]
Common Mistakes:
  • Filtering before grouping
  • Filtering on original amount instead of totalSales
  • Filtering on wrong field name
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