- 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
Count unique items in array-based fields across all MongoDB documents?
To count unique items in array-based fields, use $group along with aggregate(). Let us create a collection with documents −
> db.demo493.insertOne({"SubjectName":["MySQL","MongoDB","Java"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e849f97b0f3fa88e22790c4") } > db.demo493.insertOne({"SubjectName":["C++","MongoDB","C"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e849fa4b0f3fa88e22790c5") } > db.demo493.insertOne({"SubjectName":["MySQL","MongoDB","C"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e849fb2b0f3fa88e22790c6") }
Display all documents from a collection with the help of find() method −
> db.demo493.find();
This will produce the following output −
{ "_id" : ObjectId("5e849f97b0f3fa88e22790c4"), "SubjectName" : [ "MySQL", "MongoDB", "Java" ] } { "_id" : ObjectId("5e849fa4b0f3fa88e22790c5"), "SubjectName" : [ "C++", "MongoDB", "C" ] } { "_id" : ObjectId("5e849fb2b0f3fa88e22790c6"), "SubjectName" : [ "MySQL", "MongoDB", "C" ] }
Following is the query to count unique items in array-based fields across all documents −
> db.demo493.aggregate([ ... { $unwind: "$SubjectName" }, ... { $group: { _id: "$SubjectName", Frequency: { $sum : 1 } } } ... ] ... );
This will produce the following output −
{ "_id" : "C++", "Frequency" : 1 } { "_id" : "C", "Frequency" : 2 } { "_id" : "Java", "Frequency" : 1 } { "_id" : "MySQL", "Frequency" : 2 } { "_id" : "MongoDB", "Frequency" : 3 }
Advertisements