- 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
Group query upon nested object in MongoDB?
For this, use dot notation along with $group in MongoDB. Let us create a collection with documents −
> db.demo617.insertOne( ... { ... ... "clientDetails": { ... "Name": "Chris", ... "Age":32, ... "Project":"Online Library Management System" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e99d2b86c954c74be91e69b") } > > db.demo617.insertOne( ... { ... ... "clientDetails": { ... "Name": "David", ... "Age":34, ... "Project":"Online Hospital Management System" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e99d2b86c954c74be91e69c") } > > db.demo617.insertOne( ... { ... ... "clientDetails": { ... "Name": "David", ... "Age":34, ... "Project":"Online Library Management System" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e99d2b96c954c74be91e69d") }
Display all documents from a collection with the help of find() method −
> db.demo617.find();
This will produce the following output −
{ "_id" : ObjectId("5e99d2b86c954c74be91e69b"), "clientDetails" : { "Name" : "Chris", "Age" : 32, "Project" : "Online Library Management System" } } { "_id" : ObjectId("5e99d2b86c954c74be91e69c"), "clientDetails" : { "Name" : "David", "Age" : 34, "Project" : "Online Hospital Management System" } } { "_id" : ObjectId("5e99d2b96c954c74be91e69d"), "clientDetails" : { "Name" : "David", "Age" : 34, "Project" : "Online Library Management System" } }
The group query upon nested object in MongoDB −
> db.demo617.aggregate({ $group : {_id : "$clientDetails.Project", All : { $sum : 1 }} });
This will produce the following output −
{ "_id" : "Online Hosiptal Management System", "All" : 1 } { "_id" : "Online Library Management System", "All" : 2 }
Advertisements