Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.