- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" } ] }
Advertisements