Computer >> Computer tutorials >  >> Programming >> MongoDB

Perform Group in MongoDB and sum the price record of documents


For this, use $group and within that, we need to work with $sum to add. Let us create a collection with documents −

> db.demo527.insertOne({"Price":45.5});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8aff2fef4dcbee04fbbbdc")
}
> db.demo527.insertOne({"Price":55.5});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8aff34ef4dcbee04fbbbdd")
}
> db.demo527.insertOne({"Price":100.4});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8aff39ef4dcbee04fbbbde")
}
> db.demo527.insertOne({"Price":200.6});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8aff40ef4dcbee04fbbbdf")
}

Display all documents from a collection with the help of find() method −

> db.demo527.find();

This will produce the following output −

{ "_id" : ObjectId("5e8aff2fef4dcbee04fbbbdc"), "Price" : 45.5 }
{ "_id" : ObjectId("5e8aff34ef4dcbee04fbbbdd"), "Price" : 55.5 }
{ "_id" : ObjectId("5e8aff39ef4dcbee04fbbbde"), "Price" : 100.4 }
{ "_id" : ObjectId("5e8aff40ef4dcbee04fbbbdf"), "Price" : 200.6 }

Following is the query to sum the price records −

> db.demo527.aggregate([ { $group: { _id:null, totalPrice:{"$sum":"$Price"}} } ])

This will produce the following output −

{ "_id" : null, "totalPrice" : 402 }