Get the length of distinct values in an array with MongoDB


To get distinct values, use MongoDB DISTINCT. For length, use LENGTH(). Let us create a collection with documents −

> db.demo36.insertOne({"Names":["Chris","Bob"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17643bcfb11e5c34d898d4")
}
> db.demo36.insertOne({"Names":["Mike","Sam","Carol"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e176449cfb11e5c34d898d5")
}
> db.demo36.insertOne({"Names":["Chris","Bob","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17645bcfb11e5c34d898d6")
}

Display all documents from a collection with the help of find() method −

> db.demo36.find();

This will produce the following output −

{ "_id" : ObjectId("5e17643bcfb11e5c34d898d4"), "Names" : [ "Chris", "Bob" ] }
{ "_id" : ObjectId("5e176449cfb11e5c34d898d5"), "Names" : [ "Mike", "Sam", "Carol" ] }
{ "_id" : ObjectId("5e17645bcfb11e5c34d898d6"), "Names" : [ "Chris", "Bob", "David" ] }

Following is the query to get the length −

> db.demo36.distinct('Names').length;

This will produce the following output −

6

Updated on: 02-Apr-2020

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements