MongoDB – Distinct() Method
In MongoDB, the 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 this method 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, , 45], then this method considered 2, , and 45 separately.
- In this method, you can also use indexes.
db.Collection_name.distinct( field : <string>, query : <document>, collation : <document> )
- The first parameter is the field for which to return distinct values.
- Others are optional.
- 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.
It returns an array of all the distinct values for specified fields that match to the given query.
In the following examples, we are working with:
Document: Three documents contains the details of the students
- Return name of all the student present in the collection:
Here, the distinct() method returns the value of the name field.
- Return the distinct value of the embedded field from the given collection:
Here, the distinct() method returns the value of the age field.
- Return the distinct value from an array field
Here, the distinct() method returns the value of the marks field.