0
0
MongoDBquery~5 mins

$sum accumulator in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ATo sort documents by a field
BTo find the average of numeric values
CTo add numeric values in grouped documents
DTo count the number of fields in a document
How can you count documents using $sum in an aggregation?
AUse <code>$sum: 1</code>
BUse <code>$sum: "$field"</code>
CUse <code>$sum: null</code>
DUse <code>$sum: true</code>
What happens if $sum is used on a non-numeric field?
AIt throws an error or ignores non-numeric values
BIt sums the values as strings
CIt converts values to numbers automatically
DIt counts the number of documents
In this aggregation, what does { $sum: "$price" } do?<br>
{ $group: { _id: "$category", total: { $sum: "$price" } } }
ACounts documents per category
BFinds the max price per category
CSorts categories by price
DSums the price values per category
If some documents lack the field used in $sum, what happens?
AMissing fields count as zero in the sum
BMissing fields are ignored and do not add to the sum
CThe aggregation fails
DThe sum includes null values
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.