- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $sum (aggregation)
$sum (aggregation)¶
On this page
Definition¶
-
$sum¶
Changed in version 5.0.
Calculates and returns the collective sum of numeric values.
$sum ignores non-numeric values.
$sum is available in these stages:
$addFields(Available starting in MongoDB 3.4)$bucket$bucketAuto$group$matchstage that includes an$exprexpression$project$replaceRoot(Available starting in MongoDB 3.4)$replaceWith(Available starting in MongoDB 4.2)$set(Available starting in MongoDB 4.2)$setWindowFields(Available starting in MongoDB 5.0)
In MongoDB 3.2 and earlier, $sum is available in the
$group stage only.
Syntax¶
When used in the $bucket, $bucketAuto,
$group, and $setWindowFields stages,
$sum has this syntax:
When used in other supported stages, $sum has one of
two syntaxes:
$sumhas one specified expression as its operand:$sumhas a list of specified expressions as its operand:
For more information on expressions, see Expressions.
Behavior¶
Result Data Type¶
The result will have the same type as the input except when it cannot be represented accurately in that type. In these cases:
- A 32-bit integer will be converted to a 64-bit integer if the result is representable as a 64-bit integer.
- A 32-bit integer will be converted to a double if the result is not representable as a 64-bit integer.
- A 64-bit integer will be converted to double if the result is not representable as a 64-bit integer.
Non-Numeric or Non-Existent Fields¶
If used on a field that contains both numeric and non-numeric values,
$sum ignores the non-numeric values and returns the sum of the
numeric values.
If used on a field that does not exist in any document in the collection,
$sum returns 0 for that field.
If all operands are non-numeric, $sum returns 0.
Array Operand¶
In the $group stage, if the expression resolves to an
array, $sum treats the operand as a non-numerical value.
In the other supported stages:
- With a single expression as its operand, if the expression resolves
to an array,
$sumtraverses into the array to operate on the numerical elements of the array to return a single value. - With a list of expressions as its operand, if any of the expressions
resolves to an array,
$sumdoes not traverse into the array but instead treats the array as a non-numerical value.
Examples¶
Use in $group Stage¶
Consider a sales collection with the following documents:
Grouping the documents by the day and the year of the date field,
the following operation uses the $sum accumulator to compute the
total amount and the count for each group of documents.
The operation returns the following results:
Using $sum on a non-existent field returns a value of 0.
The following operation attempts to $sum on qty:
The operation returns:
The $count aggregation accumulator can be used in place of
{ $sum : 1 } in the $group stage.
See also
Use in $project Stage¶
A collection students contains the following documents:
The following example uses the $sum in the
$project stage to calculate the total quiz scores, the
total lab scores, and the total of the final and the midterm:
The operation results in the following documents:
Use in $setWindowFields Stage¶
New in version 5.0.
Create a cakeSales collection that contains cake sales in the states
of California (CA) and Washington (WA):
This example uses $sum in the $setWindowFields
stage to output the sum of the quantity of cakes sold in each
state:
In the example:
partitionBy: "$state"partitions the documents in the collection bystate. There are partitions forCAandWA.sortBy: { orderDate: 1 }sorts the documents in each partition byorderDatein ascending order (1), so the earliestorderDateis first.outputsets thesumQuantityForStatefield to the sum of thequantityvalues using$sumthat is run in a documents window.The window contains documents between an
unboundedlower limit and thecurrentdocument in the output. This means$sumreturns the sum of thequantityvalues for the documents between the beginning of the partition and the current document.
In this output, the sum of the quantity values for CA and WA
is shown in the sumQuantityForState field: