On this page本页内容
$sum
¶Calculates and returns the sum of numeric values. $sum
ignores non-numeric values.
$sum
is available in the following stages:
$group
$project
$addFields
(Available starting in MongoDB 3.4)$set
(Available starting in MongoDB 4.2)$replaceRoot
(Available starting in MongoDB 3.4)$replaceWith
(Available starting in MongoDB 4.2)$match
stage that includes an $expr
expressionIn MongoDB 3.2 and earlier, $sum
is available in the $group
stage only.
When used in the $group
stage, $sum
has the following syntax and returns the collective sum of all the numeric values that result from applying a specified expression to each document in a group of documents that share the same group by key:
When used in the other supported stages, $sum
returns the sum of the specified expression or list of expressions for each document and has one of two syntaxes:
$sum
has one specified expression as its operand:
$sum
has a list of specified expressions as its operand:
For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
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
.
Field Values | ||
---|---|---|
{ $sum : <field> } |
Numeric |
Sum of Values |
{ $sum : <field> } |
Numeric and Non-Numeric |
Sum of Numeric Values |
{ $sum : <field> } |
Non-Numeric or Non-Existent |
0 |
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:
$sum
traverses into the array to operate on the numerical elements of the array to return a single value.$sum
does not traverse into the array but instead treats the array as a non-numerical value.$group
Stage¶Consider a 考虑一个sales
collection with the following documents:sales
集合带有以下文档:
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:
$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:
In the other supported stages:
$sum
traverses into the array to operate on the numerical elements of the array to return a single value.$sum
does not traverse into the array but instead treats the array as a non-numerical value.