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

How to calculate sum of string in MongoDB?


To calculate sum of string in MongoDB, use aggregate(). Let us create a collection with documents −

> db.demo71.insertOne({"Price":"20"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29af210912fae76b13d76e")
}
> db.demo71.insertOne({"Price":"50"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29af240912fae76b13d76f")
}
> db.demo71.insertOne({"Price":"20"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29af270912fae76b13d770")
}
> db.demo71.insertOne({"Price":"10"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29af2d0912fae76b13d771")
}

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

> db.demo71.find();

This will produce the following output −

{ "_id" : ObjectId("5e29af210912fae76b13d76e"), "Price" : "20" }
{ "_id" : ObjectId("5e29af240912fae76b13d76f"), "Price" : "50" }
{ "_id" : ObjectId("5e29af270912fae76b13d770"), "Price" : "20" }
{ "_id" : ObjectId("5e29af2d0912fae76b13d771"), "Price" : "10" }

Following is the query to calculate sum of string in MongoDB −

> db.demo71.aggregate([
... {
...    $group: {
...       _id: null,
...       TotalPrice: {
...          $sum: {
...             $toInt: "$Price"
...             }
...          }
...       }
...    }
... ]);

This will produce the following output −

{ "_id" : null, "TotalPrice" : 100 }