How to calculate a sum of specific documents using MongoDB aggregation?

MongoDBDatabaseBig Data Analytics

To sum, use $sum and to get sum of specific documents, you need to group them using $group in MongoDB.

Let us first create a collection with documents −

>db.calculateSumOfDocument.insertOne({"ListOfUsers":["Carol","Bob"],"UsersDetails":[{"FirstUser":"Carol","TotalLikes":20},{"FirstUser":"Bob","TotalLikes":45}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e084e9125ddae1f53b6220c")
}
>db.calculateSumOfDocument.insertOne({"ListOfUsers":["Carol","Bob"],"UsersDetails":[{"FirstUser":"Carol","TotalLikes":60},{"FirstUser":"Bob","TotalLikes":50}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e084f6125ddae1f53b6220d")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e084e9125ddae1f53b6220c"),
   "ListOfUsers" : [
      "Carol",
      "Bob"
   ],
   "UsersDetails" : [
      {
         "FirstUser" : "Carol",
         "TotalLikes" : 20
      },
      {
         "FirstUser" : "Bob",
         "TotalLikes" : 45
      }
   ]
}
{
   "_id" : ObjectId("5e084f6125ddae1f53b6220d"),
   "ListOfUsers" : [
      "Carol",
      "Bob"
   ],
   "UsersDetails" : [
      {
         "FirstUser" : "Carol",
         "TotalLikes" : 60
      },
      {
         "FirstUser" : "Bob",
         "TotalLikes" : 50
      }
   ]
}

Following is the query to calculate sum of specific documents using aggregation −

> db.calculateSumOfDocument.aggregate([
...    {
...       "$match": { "UsersDetails.FirstUser": "Carol" }
...    },
...    { "$unwind" : "$UsersDetails" },
...    {
...       "$match": { "UsersDetails.FirstUser": "Carol" }
...    },
...    {
...       "$group": {
...       "_id": null,
...       "total": { "$sum": "$UsersDetails.TotalLikes" }
...    }
... }
... ]);

This will produce the following output −

{ "_id" : null, "total" : 80 }
raja
Published on 31-Mar-2020 08:19:57
Advertisements