$sum (aggregation)

On this page本页内容

Definition定义

$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)(从MongoDB 3.4开始提供)
  • $set (Available starting in MongoDB 4.2)(从MongoDB 4.2开始提供)
  • $replaceRoot (Available starting in MongoDB 3.4)(从MongoDB 3.4开始提供)
  • $replaceWith (Available starting in MongoDB 4.2)(从MongoDB 4.2开始提供)
  • $match stage that includes an $expr expression包含一个$expr表达式的$match阶段,

In MongoDB 3.2 and earlier, $sum is available in the $group stage only.在MongoDB 3.2及更早版本中,$sum仅在$group阶段可用。

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:$group阶段中使用时,$sum具有以下语法,并返回将指定表达式应用于共享同一分组键的文档组中的每个文档所产生的所有数值的总和:

{ $sum: <expression> }

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返回每个文档的指定表达式或表达式列表的总和,并具有以下两种语法之一:

  • $sum has one specified expression as its operand:具有一个指定的表达式作为其操作数:

    { $sum: <expression> }
  • $sum has a list of specified expressions as its operand:将指定表达式的列表作为其操作数:

    { $sum: [ <expression1>, <expression2> ... ]  }

For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Behavior行为

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.如果在同时包含数值和非数值的字段上使用,$sum忽略非数值并返回数值之和。

If used on a field that does not exist in any document in the collection, $sum returns 0 for that field.如果在集合中的任何文档中都不存在的字段上使用,$sum会为该字段返回0

If all operands are non-numeric, $sum returns 0.如果所有操作数都是非数字的,$sum返回0

Example示例Field ValuesResults结果
{ $sum : <field> } Numeric Sum of Values
{ $sum : <field> } Numeric and Non-Numeric Sum of Numeric Values
{ $sum : <field> } Non-Numeric or Non-Existent 0

Array Operand数组操作数

In the $group stage, if the expression resolves to an array, $sum treats the operand as a non-numerical value.$group阶段,如果表达式解析为数组,$sum将操作数视为非数值。

In the other supported stages:在其他受支持的阶段:

  • With a single expression as its operand, if the expression resolves to an array, $sum traverses into the array to operate on the numerical elements of the array to return a single value.使用单个表达式作为其操作数时,如果表达式解析为数组,$sum遍历数组,对数组的数字元素进行操作,以返回单个值。
  • With a list of expressions as its operand, if any of the expressions resolves to an array, $sum does not traverse into the array but instead treats the array as a non-numerical value.使用表达式列表作为其操作数,如果任何表达式解析为数组,$sum不会遍历数组,而是将数组视为非数值。

Examples示例

Use in $group Stage$group阶段使用

Consider a sales collection with the following documents:考虑一个sales集合带有以下文档:

{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") }

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.按照date字段的日期和年份对文档进行分组,下面的操作使用$sum累加器计算每组文档的总金额和计数。

db.sales.aggregate(
   [
     {
       $group:
         {
           _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
           totalAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
           count: { $sum: 1 }
         }
     }
   ]
)

The operation returns the following results:操作返回以下结果:

{ "_id" : { "day" : 46, "year" : 2014 }, "totalAmount" : 150, "count" : 2 }
{ "_id" : { "day" : 34, "year" : 2014 }, "totalAmount" : 45, "count" : 2 }
{ "_id" : { "day" : 1, "year" : 2014 }, "totalAmount" : 20, "count" : 1 }

Using $sum on a non-existent field returns a value of 0. 对不存在的字段使用$sum返回值0The following operation attempts to $sum on qty:以下操作尝试对qty进行$sum

db.sales.aggregate(
   [
     {
       $group:
         {
           _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
           totalAmount: { $sum: "$qty" },
           count: { $sum: 1 }
         }
     }
   ]
)

The operation returns:操作返回:

{ "_id" : { "day" : 46, "year" : 2014 }, "totalAmount" : 0, "count" : 2 }
{ "_id" : { "day" : 34, "year" : 2014 }, "totalAmount" : 0, "count" : 2 }
{ "_id" : { "day" : 1, "year" : 2014 }, "totalAmount" : 0, "count" : 1 }

Use in $project Stage$project阶段使用

A collection students contains the following documents:students集合包括以下文件:

{ "_id": 1, "quizzes": [ 10, 6, 7 ], "labs": [ 5, 8 ], "final": 80, "midterm": 75 }
{ "_id": 2, "quizzes": [ 9, 10 ], "labs": [ 8, 8 ], "final": 95, "midterm": 80 }
{ "_id": 3, "quizzes": [ 4, 5, 5 ], "labs": [ 6, 5 ], "final": 78, "midterm": 70 }

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:以下示例使用$project阶段中的$sum计算测验总分、实验室总分以及期末和期中考试的总分:

db.students.aggregate([
   {
     $project: {
       quizTotal: { $sum: "$quizzes"},
       labTotal: { $sum: "$labs" },
       examTotal: { $sum: [ "$final", "$midterm" ] }
     }
   }
])

The operation results in the following documents:该操作将生成以下文档:

{ "_id" : 1, "quizTotal" : 23, "labTotal" : 13, "examTotal" : 155 }
{ "_id" : 2, "quizTotal" : 19, "labTotal" : 16, "examTotal" : 175 }
{ "_id" : 3, "quizTotal" : 14, "labTotal" : 11, "examTotal" : 148 }

In the other supported stages:在其他受支持的阶段:

  • With a single expression as its operand, if the expression resolves to an array, $sum traverses into the array to operate on the numerical elements of the array to return a single value.使用单个表达式作为其操作数时,如果表达式解析为数组,$sum遍历数组,对数组的数字元素进行操作,以返回单个值。
  • With a list of expressions as its operand, if any of the expressions resolves to an array, $sum does not traverse into the array but instead treats the array as a non-numerical value.使用表达式列表作为其操作数,如果任何表达式解析为数组,$sum不会遍历数组,而是将数组视为非数值。