How to count number of distinct values per field/ key in MongoDB?

MongoDBDatabaseBig Data Analytics

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
raja
Published on 28-Mar-2019 13:30:27
Advertisements