How to return only unique values (no duplicates) in MongoDB?


You can use distinct() to return only unique values. The syntax is as follows −

db.yourCollectionName.distinct("yourFieldName");

To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"Larry","CustomerAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ed7262f684a30fbdfd580")
}
> db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"Mike","CustomerAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ed72d2f684a30fbdfd581")
}
> db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"Sam","CustomerAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ed7322f684a30fbdfd582")
}
> db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"Carol","CustomerAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ed73a2f684a30fbdfd583")
}
> db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"David","CustomerAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ed74a2f684a30fbdfd584")
}
> db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"Chris","CustomerAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ed7582f684a30fbdfd585")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.returnOnlyUniqueValuesDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c8ed7262f684a30fbdfd580"),
   "CusomerName" : "Larry",
   "CustomerAge" : 23
}
{
   "_id" : ObjectId("5c8ed72d2f684a30fbdfd581"),
   "CusomerName" : "Mike",
   "CustomerAge" : 21
}
{
   "_id" : ObjectId("5c8ed7322f684a30fbdfd582"),
   "CusomerName" : "Sam",
   "CustomerAge" : 21
}
{
   "_id" : ObjectId("5c8ed73a2f684a30fbdfd583"),
   "CusomerName" : "Carol",
   "CustomerAge" : 25
}
{
   "_id" : ObjectId("5c8ed74a2f684a30fbdfd584"),
   "CusomerName" : "David",
   "CustomerAge" : 22
}
{
   "_id" : ObjectId("5c8ed7582f684a30fbdfd585"),
   "CusomerName" : "Chris",
   "CustomerAge" : 23
}

Here is the query to return only unique values −

> db.returnOnlyUniqueValuesDemo.distinct("CustomerAge");

The following is the output:

[ 23, 21, 25, 22 ]

Updated on: 30-Jul-2019

862 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements