MongoDB query to get only distinct values


To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.

Let us create a collection with documents −

> db.demo287.insertOne({"details":{"AllVowels":["a","u","u","o","e","a","o","i"]}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4c014cf49383b52759cbbd")
}

Display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5e4c014cf49383b52759cbbd"),
   "details" : {
      "AllVowels" : [ "a", "u", "u", "o", "e", "a", "o", "i" ]
   }
}

Following is the query to get distinct values −

> db.demo287.distinct("details.AllVowels");

This will produce the following output −

[ "a", "e", "i", "o", "u" ]

Updated on: 31-Mar-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements