- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 }
- Related Articles
- Calculate frequency of duplicate names from NAME field using MongoDB aggregate?
- Get the duplicate values of a field in MongoDB?
- Group with multiple fields and get the count of duplicate field values grouped together in MongoDB
- How to aggregate sum in MongoDB to get the total count?
- MongoDB aggregate to get the Mean daily average count of recorded documents in a collection?
- How to get only values in arrays with MongoDB aggregate?
- MongoDB Aggregate JSON array field for the matching field of other collection?
- MongoDB aggregate $slice to get the length of the array
- Get the count of duplicate values from a single column in MySQL?
- How can I aggregate collection and group by field count in MongoDB?
- How to count number of distinct values per field/ key in MongoDB?
- Get the average of marks in MongoDB with aggregate?
- How to get tag count in MongoDB query results based on list of names?
- How to get distinct list of sub-document field values in MongoDB?
- MongoDB query to get specific list of names from documents where the value of a field is an array

Advertisements