Retrieve Distinct Values of a Field

Info With Circle IconCreated with Sketch.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>

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.

Info With Circle IconCreated with Sketch.Note

This example connects to an instance of MongoDB using a connection string. To learn more about connecting to your MongoDB instance, see the connection guide.

1const { MongoClient } = require("mongodb");
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri =
5 "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
7const client = new MongoClient(uri);
9async function run() {
10 try {
11 await client.connect();
13 // define a database and collection on which to run the method
14 const database = client.db("sample_mflix");
15 const movies = database.collection("movies");
17 // specify the document field
18 const fieldName = "year";
20 // specify an optional query document
21 const query = { directors: "Barbra Streisand" };
23 const distinctValues = await movies.distinct(fieldName, query);
25 console.log(distinctValues);
26 } finally {
27 await client.close();
28 }
Give Feedback