MongoDB aggregation to sum product price with similar IDs

MongoDBDatabaseBig Data Analytics

You need to use $group to group documents with specified _id expression. Let us first create a collection with documents −

> db.aggreagateDemo.insertOne({"Product_Id":1,"ProductPrice":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06d3c025ddae1f53b621d9")
}
> db.aggreagateDemo.insertOne({"Product_Id":2,"ProductPrice":100});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06d3c625ddae1f53b621da")
}
> db.aggreagateDemo.insertOne({"Product_Id":2,"ProductPrice":500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06d3cb25ddae1f53b621db")
}
> db.aggreagateDemo.insertOne({"Product_Id":1,"ProductPrice":150});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e06d3d125ddae1f53b621dc")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.aggreagateDemo.find().pretty();

This will produce the following output −

{
   "_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
}

Here is the query to perform aggregation and group with id −

> db.aggreagateDemo.aggregate([
...    {
...       $group: {
...       _id: "$Product_Id",
...          TotalValue:{$sum: "$ProductPrice"}
...       }
...    }
... ]
... );

This will produce the following output −

{ "_id" : 2, "TotalValue" : 600 }
{ "_id" : 1, "TotalValue" : 200 }
raja
Published on 27-Mar-2020 17:07:13
Advertisements