
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
Count Frequency of Every Element in an Array using MongoDB Query
To count, you can also use aggregate() along with $sum. Let us create a collection with documents −
> db.demo184.insertOne({"Names":["Chris","David","Bob"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3999fb9e4f06af55199805") } > db.demo184.insertOne({"Names":["Chris","Mike"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e399a0d9e4f06af55199806") } > db.demo184.insertOne({"Names":["Chris","Bob","Carol"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e399a209e4f06af55199807") }
Display all documents from a collection with the help of find() method −
> db.demo184.find();
This will produce the following output −
{ "_id" : ObjectId("5e3999fb9e4f06af55199805"), "Names" : [ "Chris", "David", "Bob" ] } { "_id" : ObjectId("5e399a0d9e4f06af55199806"), "Names" : [ "Chris", "Mike" ] } { "_id" : ObjectId("5e399a209e4f06af55199807"), "Names" : [ "Chris", "Bob", "Carol" ] }
Following is the query to count the frequency of every element −
> db.demo184.aggregate([ ... { "$unwind" : "$Names" }, ... { "$group": { "_id": "$Names", "count": { "$sum": 1} } }, ... { "$group": { ... "_id": null, ... "counts": { ... "$push": { ... "k": "$_id", ... "v": "$count" ... } ... } ... } }, ... { "$replaceRoot": { ... "newRoot": { "$arrayToObject": "$counts" } ... } } ...])
This will produce the following output −
{ "Carol" : 1, "David" : 1, "Chris" : 3, "Bob" : 2, "Mike" : 1 }
Advertisements