- 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
MongoDB query for counting the distinct values across all documents?
For this, use aggregate() in MongoDB. Let us create a collection with documents −
> db.demo718.insertOne( ... { ... "id":101, ... "details": ... { ... "OtherDetails": ["Chris", "Mike", "Sam"], "GroupName": ["Group-1"], "Info": [] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eaae25843417811278f5880") } > db.demo718.insertOne( ... { ... "id":102, ... "details": ... { ... "OtherDetails": ["Chris", "David"], "GroupName": ["Group-1"], "Info": [] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eaae25943417811278f5881") }
Display all documents from a collection with the help of find() method −
> db.demo718.find();
This will produce the following output −
{ "_id" : ObjectId("5eaae25843417811278f5880"), "id" : 101, "details" : { "OtherDetails" : [ "Chris", "Mike", "Sam" ], "GroupName" : [ "Group-1" ], "Info" : [ ] } } { "_id" : ObjectId("5eaae25943417811278f5881"), "id" : 102, "details" : { "OtherDetails" : [ "Chris", "David" ], "GroupName" : [ "Group-1" ], "Info" : [ ] } }
Following is the query to count the distinct values across all documents −
> db.demo718.aggregate([ ... { ... $unwind: "$details.GroupName" ... }, ... { ... $match: { ... "details.GroupName": "Group-1" ... } ... }, ... { ... $unwind: "$details.OtherDetails" ... }, ... { ... $group: { ... _id: "$details.GroupName", ... OtherDetailsUnique: { ... $addToSet: "$details.OtherDetails" ... } ... } ... }, ... { ... $project: { ... _id : 0, ... GROUP_NAME: "$_id", ... OtherDetailsUniqueCount: { ... $size: "$OtherDetailsUnique" ... } ... } ... } ... ])
This will produce the following output −
{ "GROUP_NAME" : "Group-1", "OtherDetailsUniqueCount" : 4 }
Advertisements