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" ]

Updated on: 14-May-2020

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements