 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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 distinct value in MongoDB?
Use the concept of length to count distinct value. Following is the syntax −
db.yourCollectionName.distinct("yourFieldName").length; Let us create a collection with documents −
> db.countDistinctDemo.insertOne({"StudentName":"John"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cbd6166de8cc557214c0dfa") } > db.countDistinctDemo.insertOne({"StudentName":"Chris"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cbd616ade8cc557214c0dfb") } > db.countDistinctDemo.insertOne({"StudentName":"Chris"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cbd616cde8cc557214c0dfc") } > db.countDistinctDemo.insertOne({"StudentName":"Carol"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cbd6170de8cc557214c0dfd") } > db.countDistinctDemo.insertOne({"StudentName":"David"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cbd6175de8cc557214c0dfe") } > db.countDistinctDemo.insertOne({"StudentName":"Carol"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5cbd6181de8cc557214c0dff") } Display all documents from a collection with the help of find() method −
> db.countDistinctDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cbd6166de8cc557214c0dfa"), "StudentName" : "John" } { "_id" : ObjectId("5cbd616ade8cc557214c0dfb"), "StudentName" : "Chris" } { "_id" : ObjectId("5cbd616cde8cc557214c0dfc"), "StudentName" : "Chris" } { "_id" : ObjectId("5cbd6170de8cc557214c0dfd"), "StudentName" : "Carol" } { "_id" : ObjectId("5cbd6175de8cc557214c0dfe"), "StudentName" : "David" } { "_id" : ObjectId("5cbd6181de8cc557214c0dff"), "StudentName" : "Carol" } Following is the query to count distinct value −
> db.countDistinctDemo.distinct("StudentName").length; This will produce the following output −
4
Advertisements
 