MongoDB query to add up the values of a specific field in documents

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

> db.demo677.insertOne({Value:10});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea421f404263e90dac943f8")
}
> db.demo677.insertOne({Value:50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea421f704263e90dac943f9")
}
> db.demo677.insertOne({Value:20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea421fa04263e90dac943fa")
}
> db.demo677.insertOne({Value:20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea421fe04263e90dac943fb")
}

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

> db.demo677.find();

This will produce the following output −

{ "_id" : ObjectId("5ea421f404263e90dac943f8"), "Value" : 10 }
{ "_id" : ObjectId("5ea421f704263e90dac943f9"), "Value" : 50 }
{ "_id" : ObjectId("5ea421fa04263e90dac943fa"), "Value" : 20 }
{ "_id" : ObjectId("5ea421fe04263e90dac943fb"), "Value" : 20 }

Following is the query to add up the values of a specific field −

> db.demo677.aggregate({ $group: { _id : null, sum : { $sum: "$Value" } } });

This will produce the following output −

{ "_id" : null, "sum" : 100 }
raja
Published on 13-May-2020 10:08:02
Advertisements