Recall & Review
beginner
What does the
$sum accumulator do in MongoDB aggregation?It adds up all the numeric values from the documents in a group and returns the total sum.
Click to reveal answer
beginner
How do you use
$sum to count the number of documents in a group?Use
$sum: 1 inside $group stage to add 1 for each document, effectively counting them.Click to reveal answer
intermediate
Can
$sum be used with non-numeric fields?No,
$sum only works with numeric values. Non-numeric values will cause errors or be ignored.Click to reveal answer
beginner
Example: What does this aggregation do?
{ $group: { _id: "$category", total: { $sum: "$price" } } }It groups documents by the
category field and calculates the total sum of the price field for each category.Click to reveal answer
intermediate
What happens if you use
$sum with a field that sometimes is missing in documents?Missing fields are treated as
null and do not add to the sum. Only existing numeric values are summed.Click to reveal answer
What is the purpose of the
$sum accumulator in MongoDB?✗ Incorrect
$sum adds numeric values from documents in a group to get a total sum.
How can you count documents using
$sum in an aggregation?✗ Incorrect
Using $sum: 1 adds 1 for each document, counting them.
What happens if
$sum is used on a non-numeric field?✗ Incorrect
$sum requires numeric values; non-numeric values cause errors or are ignored.
In this aggregation, what does
{ $sum: "$price" } do?<br>{ $group: { _id: "$category", total: { $sum: "$price" } } }✗ Incorrect
It sums the price field values for each category.
If some documents lack the field used in
$sum, what happens?✗ Incorrect
Missing fields are treated as null and do not add to the sum.
Explain how the
$sum accumulator works in MongoDB aggregation and give an example use case.Think about adding numbers or counting items in groups.
You got /4 concepts.
What should you be careful about when using
$sum with fields that might be missing or non-numeric?Consider data types and missing data.
You got /3 concepts.