- 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
Using MongoDB Aggregate and GroupBy to get the frequency of name record
Let us first create a collection with documents −
> db.demo232.insertOne({_id:101,Name:"Chris"}); { "acknowledged" : true, "insertedId" : 101 } > db.demo232.insertOne({_id:102,Name:"Bob"}); { "acknowledged" : true, "insertedId" : 102 } > db.demo232.insertOne({_id:103,Name:"Bob"}); { "acknowledged" : true, "insertedId" : 103 } > db.demo232.insertOne({_id:104,Name:"David"}); { "acknowledged" : true, "insertedId" : 104 } > db.demo232.insertOne({_id:105,Name:"Chris"}); { "acknowledged" : true, "insertedId" : 105 }
Display all documents from a collection with the help of find() method −
> db.demo232.find();
This will produce the following output −
{ "_id" : 101, "Name" : "Chris" } { "_id" : 102, "Name" : "Bob" } { "_id" : 103, "Name" : "Bob" } { "_id" : 104, "Name" : "David" } { "_id" : 105, "Name" : "Chris" }
Following is the query to get the frequency of name record in MongoDB −
> db.demo232.aggregate( { $group : {_id : "$Name", Frequency : { $sum : 1 }} } );
This will produce the following output −
{ "_id" : "David", "Frequency" : 1 } { "_id" : "Bob", "Frequency" : 2 } { "_id" : "Chris", "Frequency" : 2 }
- Related Articles
- Calculate frequency of duplicate names from NAME field using MongoDB aggregate?
- Use MongoDB Aggregate and select only top record (descending)
- Get the first element in an array and return using MongoDB Aggregate?
- MongoDB aggregate $slice to get the length of the array
- Get substring in MongoDB aggregate
- MongoDB Aggregate to get average from document and of array elements?
- Get the average of marks in MongoDB with aggregate?
- MongoDB GroupBy to set status
- Get Random record from MongoDB?
- Using $redact in MongoDB aggregate?
- How to aggregate sum in MongoDB to get the total count?
- MongoDB aggregate to get the count of field values of corresponding duplicate names?
- Get distinct record values in MongoDB?
- How to get only values in arrays with MongoDB aggregate?
- MongoDB Aggregate to limit the number of records

Advertisements