
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate Frequency of Duplicate Names Using MongoDB Aggregate
To calculate frequency, group with $group in aggregate(). Let us create a collection with documents −
> db.demo635.insertOne({Name:"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c10f06c954c74be91e6cc") } > db.demo635.insertOne({Name:"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c10f46c954c74be91e6cd") } > db.demo635.insertOne({Name:"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c10f66c954c74be91e6ce") } > db.demo635.insertOne({Name:"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c10f86c954c74be91e6cf") } > db.demo635.insertOne({Name:"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c10fb6c954c74be91e6d0") } > db.demo635.insertOne({Name:"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e9c10fc6c954c74be91e6d1") }
Display all documents from a collection with the help of find() method −
> db.demo635.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c10f06c954c74be91e6cc"), "Name" : "Chris" } { "_id" : ObjectId("5e9c10f46c954c74be91e6cd"), "Name" : "David" } { "_id" : ObjectId("5e9c10f66c954c74be91e6ce"), "Name" : "David" } { "_id" : ObjectId("5e9c10f86c954c74be91e6cf"), "Name" : "Chris" } { "_id" : ObjectId("5e9c10fb6c954c74be91e6d0"), "Name" : "Bob" } { "_id" : ObjectId("5e9c10fc6c954c74be91e6d1"), "Name" : "Chris" }
Following is the query to calculate frequency using MongoDB aggregate framework −
> db.demo635.aggregate([ ... { $unwind: "$Name" }, ... { $group: { "_id": "$Name", TotalFrequency: { $sum : 1 } } } ... ] ... );
This will produce the following output −
{ "_id" : "David", "TotalFrequency" : 2 } { "_id" : "Bob", "TotalFrequency" : 1 } { "_id" : "Chris", "TotalFrequency" : 3 }
Advertisements