Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Retrieve Distinct Values of a Field

Note

If you specify a callback method, distinct() returns nothing. If you do not specify one, this method returns a Promise that resolves to the result object when it completes. See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.

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 = collection.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 = collection.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.

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 ]
←  Count DocumentsRun a Command →