Open In App
Related Articles

MongoDB – Distinct() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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.

  • If you are using this method in the sharded cluster, then it may return orphaned documents.
  • In this method, if the value of the given field is an array, then this method will be considered each array value as a separate value. For example, if the value of the specified field is [2, [23], 45], then this method considered ‘2’, ‘[23]’, and ’45’ separately.
  • In this method, you can also use indexes to enhance performance.

Syntax:

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

Parameters:

  • The first parameter is the field for which to return distinct values.
  • Others are optional.

Optional Parameters:

  • query: A query that specifies the documents from which to retrieve the distinct values.
  • collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.

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

  • Return name of all the student present in the collection:
db.student.distinct("name")

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

  • Return the distinct value of the embedded field from the given collection:
db.student.distinct("detail.age")

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

  • Return the distinct value from an array field
db.student.distinct("marks")

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


Last Updated : 05 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads