$sum (aggregation)

Definition

  • $sum
  • Calculates and returns the sum of numeric values. $sumignores non-numeric values.

$sum is available in the following stages:

When used in the $group stage, $sum has thefollowing syntax and returns the collective sum of all the numericvalues that result from applying a specified expression to eachdocument in a group of documents that share the same group by key:

  1. { $sum: <expression> }

When used in the other supported stages, $sum returns thesum of the specified expression or list of expressions for eachdocument and has one of two syntaxes:

  • $sum has one specified expression as its operand:
  1. { $sum: <expression> }
  • $sum has a list of specified expressions as itsoperand:
  1. { $sum: [ <expression1>, <expression2> ... ] }

For more information on expressions, seeExpressions.

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 thenumeric 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.

ExampleField ValuesResults
{ $sum : <field> }NumericSum of Values
{ $sum : <field> }Numeric and Non-NumericSum of Numeric Values
{ $sum : <field> }Non-Numeric or Non-Existent0

Array Operand

In the $group stage, if the expression resolves to anarray, $sum treats the operand as a non-numerical value.

In the other supported stages:

  • With a single expression as its operand, if the expression resolvesto an array, $sum traverses into the array to operate on thenumerical elements of the array to return a single value.
  • With a list of expressions as its operand, if any of the expressionsresolves to an array, $sum does not traverse into thearray but instead treats the array as a non-numerical value.

Examples

Use in $group Stage

Consider a sales collection with the following documents:

  1. { "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }
  2. { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }
  3. { "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }
  4. { "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }
  5. { "_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 thetotal amount and the count for each group of documents.

  1. db.sales.aggregate(
  2. [
  3. {
  4. $group:
  5. {
  6. _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
  7. totalAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
  8. count: { $sum: 1 }
  9. }
  10. }
  11. ]
  12. )

The operation returns the following results:

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

Using $sum on a non-existent field returns a value of 0.The following operation attempts to $sum on qty:

  1. db.sales.aggregate(
  2. [
  3. {
  4. $group:
  5. {
  6. _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
  7. totalAmount: { $sum: "$quantity" },
  8. count: { $sum: 1 }
  9. }
  10. }
  11. ]
  12. )

The operation returns:

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

Use in $project Stage

A collection students contains the following documents:

  1. { "_id": 1, "quizzes": [ 10, 6, 7 ], "labs": [ 5, 8 ], "final": 80, "midterm": 75 }
  2. { "_id": 2, "quizzes": [ 9, 10 ], "labs": [ 8, 8 ], "final": 95, "midterm": 80 }
  3. { "_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, thetotal lab scores, and the total of the final and the midterm:

  1. db.students.aggregate([
  2. {
  3. $project: {
  4. quizTotal: { $sum: "$quizzes"},
  5. labTotal: { $sum: "$labs" },
  6. examTotal: { $sum: [ "$final", "$midterm" ] }
  7. }
  8. }
  9. ])

The operation results in the following documents:

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

In the other supported stages:

  • With a single expression as its operand, if the expression resolvesto an array, $sum traverses into the array to operate on thenumerical elements of the array to return a single value.
  • With a list of expressions as its operand, if any of the expressionsresolves to an array, $sum does not traverse into thearray but instead treats the array as a non-numerical value.