- 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 query to group several fields using aggregation framework?
To group several fields, use $group in MongoDB. Let us create a collection with documents −
> db.demo192.insertOne({"Name":"Chris","Age":22}); { "acknowledged" : true, "insertedId" : ObjectId("5e3adb9f03d395bdc21346cd") } > db.demo192.insertOne({"Name":"David","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e3adba103d395bdc21346ce") } > db.demo192.insertOne({"Name":"Chris","Age":22}); { "acknowledged" : true, "insertedId" : ObjectId("5e3adba503d395bdc21346cf") } > db.demo192.insertOne({"Name":"Mike","Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e3adbbf03d395bdc21346d0") }
Display all documents from a collection with the help of find() method −
> db.demo192.find();
This will produce the following output −
{ "_id" : ObjectId("5e3adb9f03d395bdc21346cd"), "Name" : "Chris", "Age" : 22 } { "_id" : ObjectId("5e3adba103d395bdc21346ce"), "Name" : "David", "Age" : 21 } { "_id" : ObjectId("5e3adba503d395bdc21346cf"), "Name" : "Chris", "Age" : 22 } { "_id" : ObjectId("5e3adbbf03d395bdc21346d0"), "Name" : "Mike", "Age" : 24 }
Following is the query to group several fields using aggregation framework −
> db.demo192.aggregate([{$group:{_id:{Age:"$Age",Name:"$Name"}}}]);
This will produce the following output −
{ "_id" : { "Age" : 24, "Name" : "Mike" } } { "_id" : { "Age" : 21, "Name" : "David" } } { "_id" : { "Age" : 22, "Name" : "Chris" } }
Advertisements