How to aggregate sum in MongoDB to get the total count?

MongoDBDatabaseBig Data Analytics

To aggregate sum in MongoDB to get the total count, you can use the $sum operator. To understand the above concept, let us create a collection with the document −

> db.aggregateSumDemo.insertOne({"CustomerName":"Larry","Amount":140});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8baa0680f10143d8431e18")
}
> db.aggregateSumDemo.insertOne({"CustomerName":"Mike","Amount":160});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8baa1380f10143d8431e19")
}
> db.aggregateSumDemo.insertOne({"CustomerName":"Sam","Amount":300});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8baa1c80f10143d8431e1a")
}
> db.aggregateSumDemo.insertOne({"CustomerName":"David","Amount":500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8baa2580f10143d8431e1b")
}

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

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

The following is the output −

{
   "_id" : ObjectId("5c8baa0680f10143d8431e18"),
   "CustomerName" : "Larry",
   "Amount" : 140
}
{
   "_id" : ObjectId("5c8baa1380f10143d8431e19"),
   "CustomerName" : "Mike",
   "Amount" : 160
}
{
   "_id" : ObjectId("5c8baa1c80f10143d8431e1a"),
   "CustomerName" : "Sam",
   "Amount" : 300
}
{
   "_id" : ObjectId("5c8baa2580f10143d8431e1b"),
   "CustomerName" : "David",
   "Amount" : 500
}

Here is the query to get the total count.

Case 1 − The query is as follows −

> db.aggregateSumDemo.aggregate([ {
   ... $group: {
      ... _id: null,
      ... "TotalCount": {
         ... $sum:1
      ... }
   ... }
... } ] );

The following is the output −

{ "_id" : null, "TotalCount" : 4 }

Here is the query to aggregate sum in MongoDB to get the total sum.

Case 2 − The query is as follows −

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

The following is the output −

{ "_id" : null, "TotalAmount" : 1100 }
raja
Published on 29-Mar-2019 15:53:25
Advertisements