Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB aggregation to sum product price with similar IDs
To sum product prices with similar IDs in MongoDB, use the $group stage in aggregation pipeline with $sum operator. This groups documents by a specified field and calculates the total for each group.
Syntax
db.collection.aggregate([
{
$group: {
_id: "$groupingField",
totalFieldName: { $sum: "$fieldToSum" }
}
}
]);
Sample Data
db.aggreagateDemo.insertMany([
{"Product_Id": 1, "ProductPrice": 50},
{"Product_Id": 2, "ProductPrice": 100},
{"Product_Id": 2, "ProductPrice": 500},
{"Product_Id": 1, "ProductPrice": 150}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e06d3c025ddae1f53b621d9"),
ObjectId("5e06d3c625ddae1f53b621da"),
ObjectId("5e06d3cb25ddae1f53b621db"),
ObjectId("5e06d3d125ddae1f53b621dc")
]
}
Display all documents to verify the data ?
db.aggreagateDemo.find().pretty();
{
"_id": ObjectId("5e06d3c025ddae1f53b621d9"),
"Product_Id": 1,
"ProductPrice": 50
}
{
"_id": ObjectId("5e06d3c625ddae1f53b621da"),
"Product_Id": 2,
"ProductPrice": 100
}
{
"_id": ObjectId("5e06d3cb25ddae1f53b621db"),
"Product_Id": 2,
"ProductPrice": 500
}
{
"_id": ObjectId("5e06d3d125ddae1f53b621dc"),
"Product_Id": 1,
"ProductPrice": 150
}
Aggregation to Sum Prices by Product ID
Group documents by Product_Id and sum the ProductPrice for each group ?
db.aggreagateDemo.aggregate([
{
$group: {
_id: "$Product_Id",
TotalValue: { $sum: "$ProductPrice" }
}
}
]);
{ "_id": 2, "TotalValue": 600 }
{ "_id": 1, "TotalValue": 200 }
How It Works
-
$groupstage groups documents by the_idfield (set to$Product_Id) -
$sumoperator calculates the total ofProductPricefor each group - Product_Id 1: 50 + 150 = 200
- Product_Id 2: 100 + 500 = 600
Conclusion
Use $group with $sum in MongoDB aggregation to calculate totals for documents with similar field values. This is essential for generating summary reports and calculating aggregated values from your data.
Advertisements
