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

  • $group stage groups documents by the _id field (set to $Product_Id)
  • $sum operator calculates the total of ProductPrice for 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.

Updated on: 2026-03-15T01:48:58+05:30

489 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements