MongoDB query to sum specific key values with terminal commands?

MongoDBDatabaseBig Data Analytics

For this, use $match along with aggregate(). Let us create a collection with documents −

> db.demo329.insertOne({"Name":"Chris","Age":21,"Marks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516f28f8647eb59e56207d")
}
> db.demo329.insertOne({"Name":"David","Age":21,"Marks":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516f28f8647eb59e56207e")
}
> db.demo329.insertOne({"Name":"Mike","Age":21,"Marks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516f29f8647eb59e56207f")
}
> db.demo329.insertOne({"Name":"David","Age":21,"Marks":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516f29f8647eb59e562080")
}

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

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

This will produce the following output:

{
   "_id" : ObjectId("5e516f28f8647eb59e56207d"),
   "Name" : "Chris",
   "Age" : 21,
   "Marks" : 45
}
{
   "_id" : ObjectId("5e516f28f8647eb59e56207e"),
   "Name" : "David",
   "Age" : 21,
   "Marks" : 56
}
{
   "_id" : ObjectId("5e516f29f8647eb59e56207f"),
   "Name" : "Mike",
   "Age" : 21,
   "Marks" : 78
}
{
   "_id" : ObjectId("5e516f29f8647eb59e562080"),
   "Name" : "David",
   "Age" : 21,
   "Marks" : 89
}

Following is the query to sum key values −

> db.demo329.aggregate([
...    {
...       $match: {
...          $and: [
...             { 'Name': 'David'},
...             { Age:21}
..          ]
...       }
...    },
...    {
...       $group: {
...          _id: null,
...          TotalMarks: { $sum: "$Marks" }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : null, "TotalMarks" : 145 }
raja
Published on 02-Apr-2020 06:39:41
Advertisements