 
  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
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
Advertisements
 