How to sum the value of a key across all documents in a MongoDB collection?


To get sum the value of a key across all documents in a MongoDB collection, you can use aggregate().

To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.sumOfValueDemo.insertOne({"Name":"Larry","Amount":14.50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ee7272f684a30fbdfd592")
}
> db.sumOfValueDemo.insertOne({"Name":"Mike","Amount":15.68});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ee7342f684a30fbdfd593")
}
> db.sumOfValueDemo.insertOne({"Name":"Carol","Amount":50.32});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ee7412f684a30fbdfd594")
}
> db.sumOfValueDemo.insertOne({"Name":"David","Amount":120.90});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ee7532f684a30fbdfd595")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c8ee7272f684a30fbdfd592"),
   "Name" : "Larry",
   "Amount" : 14.5
}
{
   "_id" : ObjectId("5c8ee7342f684a30fbdfd593"),
   "Name" : "Mike",
   "Amount" : 15.68
}
{
   "_id" : ObjectId("5c8ee7412f684a30fbdfd594"),
   "Name" : "Carol",
   "Amount" : 50.32
}
{
   "_id" : ObjectId("5c8ee7532f684a30fbdfd595"),
   "Name" : "David",
   "Amount" : 120.9
}

Here is the query to sum the value of a key across all documents in a MongoDB collection:

> db.sumOfValueDemo.aggregate({
   ... $group: {
      ... _id: '',
      ... "Amount": { $sum: '$Amount' }
   ... }
   ... }, {
      ... $project: {
         ... _id: 0,
         ... "TotalAmount": '$Amount'
      ... }
... });

The following is the output:

{ "TotalAmount" : 201.4 }

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements