MongoDB Sum

MongoDB provides $sum to get the sum of numeric values and ignores non-numeric values. With the help of the sum method, you can get the total of large sets of numbers in reports and other calculations. We can easily sum up the values of fields in the documents using the $sum operator.

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 the following 'product' 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}
]);

Here, we have explained how to perform a sum using the above data. The given statement returns the sum of the 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 }
mongodb aggregate sum

You can see in the results that after running the query we got the total amount, quantity and count of metal 'steel', 'alloy' and 'iron'.







Read more articles


General Knowledge



Learn Popular Language