Articles → MONGODB → $Sum and $Group Operators In MongoDB
$Sum and $Group Operators In MongoDB
Purpose
Sales Table
db.sales.insertMany([
{ "_id": 1, "product": "A", "quantity": 5, "price": 10 },
{ "_id": 2, "product": "B", "quantity": 3, "price": 15 },
{ "_id": 3, "product": "A", "quantity": 2, "price": 12 },
{ "_id": 4, "product": "C", "quantity": 6, "price": 8 }
])
Sum Operator
db.sales.aggregate([
{
$group: {
_id: "$product", // Group by the "product" field
totalSales: {
$sum: { // Use $sum to calculate the total sales within each group
$multiply: ["$quantity", "$price"] // Multiply quantity by price for each document
}
}
}
}
])
Group Stage
Output
Click to Enlarge