- 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 to get the count of field values of corresponding duplicate names?
Let us see an example and create a collection with documents −
> db.demo558.insertOne( ... { ... _id : 100, ... CountryCode:101, ... details: [ ... { ... Name:"Chris", ... Subject:"MySQL" ... }, ... { ... Name:"Chris", ... Subject:"MongoDB" ... }, ... { ... Name:"Chris", ... Subject:"Java" ... }, ... { ... Name:"Bob", ... Subject:"Python" ... }, ... { ... Name:"Bob", ... Subject:"Java" ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : 100 }
Display all documents from a collection with the help of find() method −
> db.demo558.find();
This will produce the following output −
{ "_id" : 100, "CountryCode" : 101, "details" : [ { "Name" : "Chris", "Subject" : "MySQL" }, { "Name" : "Chris", "Subject" : "MongoDB" }, { "Name" : "Chris", "Subject" : "Java" }, { "Name" : "Bob", "Subject" : "Python" }, { "Name" : "Bob", "Subject" : "Java" } ] }
Following is the query to get the count −
> db.demo558.aggregate([ ... {$unwind: "$details" }, ... {$group: { _id: "$details.Name", NameCount:{$sum : 1}, Subject : {$push: "$details.Subject"}}}, ... {$project: { NameCount: 1, SubjectCount : {$size: "$Subject"}}} ... ]).pretty()
This will produce the following output −
{ "_id" : "Bob", "NameCount" : 2, "SubjectCount" : 2 } { "_id" : "Chris", "NameCount" : 3, "SubjectCount" : 3 }
Advertisements