MongoDB Aggregate group multiple result?


To aggregate multiple result, use $group in MongoDB. Let us create a collection with documents −

> db.demo765.insertOne(
...
...    {
...       Name:"John",
...       "Category":"ComputerScience",
...       "SubjectName":"MongoDB",
...       "Marks":75
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb054525637cd592b2a4b01")
}
>
> db.demo765.insertOne(
...    {
...       Name:"John",
...       "Category":"ComputerScience",
...       "SubjectName":"MySQL",
...       "Marks":85
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb054525637cd592b2a4b02")
}
> db.demo765.insertOne(
...    {
...       Name:"Chris",
...       "Category":"10th",
...       "SubjectName":"Math",
...       "Marks":98
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eb054535637cd592b2a4b03")
}

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

> db.demo765.find();

This will produce the following output −

{ "_id" : ObjectId("5eb054525637cd592b2a4b01"), "Name" : "John", "Category" : "ComputerScience", "SubjectName" : "MongoDB", "Marks" : 75 }
{ "_id" : ObjectId("5eb054525637cd592b2a4b02"), "Name" : "John", "Category" : "ComputerScience", "SubjectName" : "MySQL", "Marks" : 85 }
{ "_id" : ObjectId("5eb054535637cd592b2a4b03"), "Name" : "Chris", "Category" : "10th", "SubjectName" : "Math", "Marks" : 98 }

Following is the query to aggregate group multiple result −

> db.demo765.aggregate([
...    { "$facet": {
...       "ListOfName": [
...          { "$group": {
...             "_id": "$Name",
...             "Marks": { "$sum": "$Marks" }
...          }},
...          { "$project": {
...             "_id": false,
...             "Name": "$_id",
...             "Marks": 1
...          }}
...       ],
...       "ListOfCategory": [
...          { "$group": {
...             "_id": "$Category",
...             "Marks": { "$sum": "$Marks" }
...          }},
...          { "$project": {
...             "_id": false,
...             "Category": "$_id",
...             "Marks": 1
...          }}
...       ]
...    }}
... ]).pretty()

This will produce the following output −

{
   "ListOfName" : [
      {
         "Marks" : 98,
         "Name" : "Chris"
      },
      {
         "Marks" : 160,
         "Name" : "John"
      }
   ],
   "ListOfCategory" : [
      {
         "Marks" : 98,
         "Category" : "10th"
      },
      {
         "Marks" : 160,
         "Category" : "ComputerScience"
      }
   ]
}

Updated on: 01-Jul-2020

601 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements