MongoDB Sum

MongoDB provides $sum to get sum of numeric values and ignores non numeric values.

Syntax of $sum

{$sum : expressions}

Here, the sum returns the sum of the specified expression or list of expressions. It is available in the group and project stages.

Example

Suppose, we have following collection.

db.product.insert([
{'item': 'iron', 'price': 120, 'quantity': 2}, 
{'item':'alloy', 'price':90, 'quantity': 1}, 
{'item':'steel', 'price':47, 'quantity': 3}, 
{'item':'alloy', 'price':70, 'quantity': 6}, 
{'item':'iron', 'price':56, 'quantity':4}
]);

The given statement returns sum of amount and total quantity of products.

db.product.aggregate( 
[
{ "$group" : 
{ "_id": "$item", 
amt: {$sum: {$multiply: ["$price", "$quantity"]}}, 
qty: {$sum: "$quantity"}, count: {$sum: 1} 
} 
}]);

Output of the above code

{ "_id" : "steel", "amt" : 141, "qty" : 3, "count" : 1 }
{ "_id" : "alloy", "amt" : 510, "qty" : 7, "count" : 2 }
{ "_id" : "iron", "amt" : 464, "qty" : 6, "count" : 2 }






Read more articles