- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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