![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
How to get unique values from MongoDB collection?
To get unique values and ignore duplicates, use distinct() in MongoDB. The distinct() finds the distinct values for a specified field across a single collection and returns the results in an array.
Let us create a collection with documents −
> db.demo704.insertOne({"LanguageCode":"hi"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ee18551299a9f98c93bd") } > db.demo704.insertOne({"LanguageCode":"en"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ee1e551299a9f98c93be") } > db.demo704.insertOne({"LanguageCode":"hi"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ee20551299a9f98c93bf") } > db.demo704.insertOne({"LanguageCode":"eo"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ee2c551299a9f98c93c0") } > db.demo704.insertOne({"LanguageCode":"eu"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ee2f551299a9f98c93c1") } > db.demo704.insertOne({"LanguageCode":"fo"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ee35551299a9f98c93c2") } > db.demo704.insertOne({"LanguageCode":"fo"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6ee37551299a9f98c93c3") }
Display all documents from a collection with the help of find() method −
> db.demo704.find();
This will produce the following output −
{ "_id" : ObjectId("5ea6ee18551299a9f98c93bd"), "LanguageCode" : "hi" } { "_id" : ObjectId("5ea6ee1e551299a9f98c93be"), "LanguageCode" : "en" } { "_id" : ObjectId("5ea6ee20551299a9f98c93bf"), "LanguageCode" : "hi" } { "_id" : ObjectId("5ea6ee2c551299a9f98c93c0"), "LanguageCode" : "eo" } { "_id" : ObjectId("5ea6ee2f551299a9f98c93c1"), "LanguageCode" : "eu" } { "_id" : ObjectId("5ea6ee35551299a9f98c93c2"), "LanguageCode" : "fo" } { "_id" : ObjectId("5ea6ee37551299a9f98c93c3"), "LanguageCode" : "fo" }
Following is the query to get unique values and display the result in an array −
> db.demo704.distinct("LanguageCode");
This will produce the following output −
[ "hi", "en", "eo", "eu", "fo" ]
Advertisements