Definição
Alterado na versão 5.0.
Calculates and returns the collective sum of numeric values. $sum ignores non-numeric values.
$sum está disponível nestes estágios:
$setWindowFields(Disponível a partir do MongoDB 5.0)
Compatibilidade
Você pode utilizar o $sum para implantações hospedadas nos seguintes ambientes:
- MongoDB Atlas: o serviço totalmente gerenciado para implantações do MongoDB na nuvem
MongoDB Enterprise: a versão autogerenciada e baseada em assinatura do MongoDB
MongoDB Community: uma versão com código disponível, de uso gratuito e autogerenciada do MongoDB
Sintaxe
When used as an accumulator, $sum has this syntax:
{ $sum: <expression> }
When not used as an accumulator, $sum has this syntax:
{ $sum: [ <expression1>, <expression2> ... ] }
Para mais informações sobre expressões, consulte Expressões.
Comportamento
Tipo de dados de resultado
O resultado terá o mesmo tipo da entrada, exceto quando não puder ser representado com precisão nesse tipo. Nesses casos:
Um número inteiro de 32 bits será convertido para um número inteiro de 64 bits se o resultado for representável como um número inteiro de 64 bits.
Um inteiro de 32 bits será convertido em double se o resultado não for representável como um inteiro de 64 bits.
Um número inteiro de 64 bits será convertido em double se o resultado não for representável como um número inteiro de 64 bits.
Campos não numéricos ou não existentes
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, non-arrays, or contain null values, $sum returns 0. For details on how $sum handles arrays, see Array Operand.
Operando de array
In the $group stage, if the expression resolves to an array, $sum treats the operand as a non-numeric value.
Nos outros estágios suportados:
With a single expression as its operand, if the expression resolves to an array,
$sumtraverses into the array to operate on the numeric 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-numeric value.
Por exemplo, quando não usado em um estágio $group:
Se o operando
$sumfor[ 2, 2 ],$sumadiciona os elementos de array e retorna 4.Se o operador
$sumfor[ 2, [ 3, 4 ] ],$sumretornará 2 porque trata a array aninhada[ 3, 4 ]como um valor não numérico.
Exemplos
Usar no estágio $group
Considere uma collection sales com os seguintes documentos:
db.sales.insertMany( [ { "_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.
db.sales.aggregate( [ { $group: { _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } }, totalAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } }, count: { $sum: 1 } } } ] )
A operação retorna os seguintes resultados:
{ "_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. The following operation attempts to $sum on qty:
db.sales.aggregate( [ { $group: { _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } }, totalAmount: { $sum: "$qty" }, count: { $sum: 1 } } } ] )
A operação retorna:
{ "_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 }
O accumulator de aggregation $count pode ser usado no lugar de { $sum : 1 } no estágio $group.
Usar no estágio $project
Uma coleção students contém os seguintes documentos:
{ "_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:
db.students.aggregate([ { $project: { quizTotal: { $sum: "$quizzes"}, labTotal: { $sum: "$labs" }, examTotal: { $sum: [ "$final", "$midterm" ] } } } ])
A operação resulta nos seguintes documentos:
{ "_id" : 1, "quizTotal" : 23, "labTotal" : 13, "examTotal" : 155 } { "_id" : 2, "quizTotal" : 19, "labTotal" : 16, "examTotal" : 175 } { "_id" : 3, "quizTotal" : 14, "labTotal" : 11, "examTotal" : 148 }
Usar no estágio $setWindowFields
Novidade na versão 5.0.
Crie uma collection cakeSales que contenha vendas de bolo nos estados da Califórnia (CA) e de Washington (WA):
db.cakeSales.insertMany( [ { _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"), state: "CA", price: 13, quantity: 120 }, { _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"), state: "WA", price: 14, quantity: 140 }, { _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"), state: "CA", price: 12, quantity: 145 }, { _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"), state: "WA", price: 13, quantity: 104 }, { _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"), state: "CA", price: 41, quantity: 162 }, { _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"), state: "WA", price: 43, quantity: 134 } ] )
This example uses $sum in the $setWindowFields stage to output the sum of the quantity of cakes sold in each state:
db.cakeSales.aggregate( [ { $setWindowFields: { partitionBy: "$state", sortBy: { orderDate: 1 }, output: { sumQuantityForState: { $sum: "$quantity", window: { documents: [ "unbounded", "current" ] } } } } } ] )
No exemplo:
partitionBy: "$state"particiona os documentos na collection porstate. Existem partições paraCAeWA.sortBy: { orderDate: 1 }classifica os documentos em cada partição pororderDateem ordem crescente (1), para que oorderDatemais antigo seja o primeiro.
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.
Neste resultado, a soma dos valores quantity para CA e WA é mostrada no campo sumQuantityForState:
{ "_id" : 4, "type" : "strawberry", "orderDate" : ISODate("2019-05-18T16:09:01Z"), "state" : "CA", "price" : 41, "quantity" : 162, "sumQuantityForState" : 162 } { "_id" : 0, "type" : "chocolate", "orderDate" : ISODate("2020-05-18T14:10:30Z"), "state" : "CA", "price" : 13, "quantity" : 120, "sumQuantityForState" : 282 } { "_id" : 2, "type" : "vanilla", "orderDate" : ISODate("2021-01-11T06:31:15Z"), "state" : "CA", "price" : 12, "quantity" : 145, "sumQuantityForState" : 427 } { "_id" : 5, "type" : "strawberry", "orderDate" : ISODate("2019-01-08T06:12:03Z"), "state" : "WA", "price" : 43, "quantity" : 134, "sumQuantityForState" : 134 } { "_id" : 3, "type" : "vanilla", "orderDate" : ISODate("2020-02-08T13:13:23Z"), "state" : "WA", "price" : 13, "quantity" : 104, "sumQuantityForState" : 238 } { "_id" : 1, "type" : "chocolate", "orderDate" : ISODate("2021-03-20T11:30:05Z"), "state" : "WA", "price" : 14, "quantity" : 140, "sumQuantityForState" : 378 }