- 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 BY array of document to get the count of repeated Age values
To GROUP BY array of the document, use $group. Let us create a collection with documents −
>db.demo559.insertOne({details:[{Name:"Chris",Age:21},{Name:"Bob",Age:22},{Name:"Carol", Age:21},{Name:"Sam",Age:21}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e8f38d954b4472ed3e8e866") }
Display all documents from a collection with the help of find() method −
> db.demo559.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e8f38d954b4472ed3e8e866"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 22 }, { "Name" : "Carol", "Age" : 21 }, { "Name" : "Sam", "Age" : 21 } ] }
Following is the query to group by an array of the document −
> db.demo559.aggregate([ ... { ... "$unwind": "$details" ... }, ... { ... "$group": { ... "_id": "$details.Age", ... "Count": { "$sum" : 1 } ... } ... }, ... { "$sort": { "_id" : 1 } } ... ])
This will produce the following output −
{ "_id" : 21, "Count" : 3 } { "_id" : 22, "Count" : 1 }
Advertisements