How to calculate sum in MongoDB with aggregate()?

MongoDBDatabaseBig Data Analytics

To get the sum, use $sum along with aggregate(). Let us create a collection with documents −

> db.demo337.insertOne({"Amount":100});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5231e5f8647eb59e56209b")
}
> db.demo337.insertOne({"Amount":500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5231e9f8647eb59e56209c")
}
> db.demo337.insertOne({"Amount":400});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5231ebf8647eb59e56209d")
}

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

> db.demo337.find();

This will produce the following output −

{ "_id" : ObjectId("5e5231e5f8647eb59e56209b"), "Amount" : 100 }
{ "_id" : ObjectId("5e5231e9f8647eb59e56209c"), "Amount" : 500 }
{ "_id" : ObjectId("5e5231ebf8647eb59e56209d"), "Amount" : 400 }

Following is the query to calculate sum in MongoDB −

> db.demo337.aggregate(
...    [
...       {
...          $group:
...          {
...             _id:null,
...             totalAmount: { $sum:"$Amount" }
...          }
...       }
...    ]
... );

This will produce the following output −

{ "_id" : null, "totalAmount" : 1000 }
raja
Published on 02-Apr-2020 10:28:14
Advertisements