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

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



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 }
Updated on: 2020-03-31T11:46:12+05:30

773 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements