Retrieve Distinct Values of a Field
You can retrieve a list of distinct values for a field across a collection by using
the collection.distinct()
method. Call the distinct()
method on a Collection
object with a document
field name parameter as a String
to produce a list that contains one of each
of the different values found in the specified document field as shown below:
const distinctValues = myColl.distinct("countries", query);
You can specify a document field within an embedded document using
dot notation. If you call
distinct()
on an document field that contains an array, the method
treats each element as a separate value. See the following example of
a method call to the wins
field in the awards
subdocument:
const distinctValues = myColl.distinct("awards.wins", query);
You can specify additional query options using the options
object passed
as the third parameter to the distinct()
method. For details on the
query parameters, see the
distinct() method in the API documentation.
If you specify a value for the document field name that is not of type
String
such as a Document
, Array
, Number
, or null
,
the method does not execute and returns a TypeMismatch
error with a
message that resembles the following:
"key" had the wrong type. Expected string, found <non-string type>
Visit Retrieve Distinct Values for more information about the distinct()
method.
Example
The following snippet retrieves a list of distinct values for the year
document field from the movies
collection. It uses a query document to
match movies that include "Barbara Streisand" as a director
.
Note
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.
If you run the preceding example, you should see the following output:
[ 1983, 1991, 1996 ]