Aggregate based on array value to sum values in different MongoDB documents?

MongoDBDatabaseBig Data Analytics

For this, use aggregate() in MongoDB. Let us first create a collection with documents −

> db.demo126.insertOne(
...    {
...       "StudentDetails" : {
...          "Number" : 1,
...          "OtherDetails" : [
...          {
...                "Name" : "Chris",
...                "Score" : 55
...
...          }
...    ].. }}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e304b3068e7f832db1a7f56")
}
>
>
> db.demo126.insertOne(
...    {
...       "StudentDetails" : {
...
...          "Number" : 2,
...          "OtherDetails" : [
...             {
...                "Name" : "Chris",
...                "Score" : 35
...
...             },
...             {
...                "Name" : "David",
...                "Score" : 87
...             }
...
...          ]
...       }}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e304b3068e7f832db1a7f57")
}

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

> db.demo126.find();

This will produce the following output −

{ "_id" : ObjectId("5e304b3068e7f832db1a7f56"), "StudentDetails" : { "Number" : 1, "OtherDetails" : [ { "Name" : "Chris", "Score" : 55 } ] } }
{ "_id" : ObjectId("5e304b3068e7f832db1a7f57"), "StudentDetails" : { "Number" : 2, "OtherDetails" : [ { "Name" : "Chris", "Score" : 35 }, { "Name" : "David", "Score" : 87 } ] } }

Following is the query to aggregate based on array value −

> db.demo126.aggregate([
...    {
...       $unwind:"$StudentDetails.OtherDetails"
...    },
...    {
...       $group:{
...          _id:"$StudentDetails.OtherDetails.Name",
...          quantity:{
...          $sum:"$StudentDetails.OtherDetails.Score"
...          }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : "David", "quantity" : 87 }
{ "_id" : "Chris", "quantity" : 90 }
raja
Published on 31-Mar-2020 11:44:38
Advertisements