
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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 }
- Related Questions & Answers
- Group all documents with common fields in MongoDB?
- JavaScript function that should count all unique items in an array
- MongoDB query for counting the distinct values across all documents?
- Filter documents in MongoDB if all keys exist as fields?
- Match MongoDB documents with fields not containing values in array?
- How to count items in array with MongoDB?
- MongoDB query to get only specific fields in nested array documents?
- Querying array of Embedded Documents in MongoDB based on Range?
- How to filter documents based on an array in MongoDB?
- MongoDB inverse of query to return all items except specific documents?
- How to sum the value of a key across all documents in a MongoDB collection?
- MongoDB aggregation to sum individual properties on an object in an array across documents
- Sort array in MongoDB query and project all fields?
- Combining unique items from arrays in MongoDB?
- Filtering MongoDB items by fields and subfields?
Advertisements