- 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
How to count number of distinct values per field/ key in MongoDB?
You can use the distinct command for this. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.distinctCountValuesDemo.insertOne({"StudentFirstName":"John","StudentFavouriteSubject":["C","C++","Java","MySQL","C","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8a39f193b406bd3df60e07") } > db.distinctCountValuesDemo.insertOne({"StudentFirstName":"Larry","StudentFavouriteSubject":["MongoDB","SQL Server"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8a3a1193b406bd3df60e08") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.distinctCountValuesDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8a39f193b406bd3df60e07"), "StudentFirstName" : "John", "StudentFavouriteSubject" : [ "C", "C++", "Java", "MySQL", "C", "C++" ] } { "_id" : ObjectId("5c8a3a1193b406bd3df60e08"), "StudentFirstName" : "Larry", "StudentFavouriteSubject" : [ "MongoDB", "SQL Server" ] }
Here is the query to find a number of distinct values per field/key −
> db.distinctCountValuesDemo.distinct('StudentFavouriteSubject');
The following is the output −
[ "C", "C++", "Java", "MySQL", "MongoDB", "SQL Server" ]
Here is the query to find the length of the distinct value in the array −
> db.distinctCountValuesDemo.distinct('StudentFavouriteSubject').length;
The following is the output −
6
Advertisements