Open In App

MongoDB – Distinct() Method

MongoDB distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters, first one is the field for which to return distinct values and the others are optional.

Syntax:



db.Collection_name.distinct(
field : <string>,
query : <document>,
collation : <document>
)

Parameters:

Optional Parameters:



Return Value:

It returns an array of all the distinct values for specified fields that match to the given query.

Examples:

In the following examples, we are working with:

Database: gfg

Collections: student

Document: Three documents contains the details of the students

db.student.distinct("name")

Here, the distinct() method returns the value of the name field.

db.student.distinct("detail.age")

Here, the distinct() method returns the value of the age field.

db.student.distinct("marks")

Here, the distinct() method returns the value of the marks field.

Article Tags :