Return a list of distinct values for the given key within a collection or within a find result set.

To call the collection.distinct() action from a Function, get a collection handle with database.collection(), and then call the handle's distinct() method, passing in the field from which you want to get distinct values, and the query object for finding the documents. The following code returns all unique values of the field "status" for all documents within the "tasks" collection:

1const taskCollection ="mongodb-atlas")
2 .db("tracker").collection("tasks");
4taskCollection.distinct("status", {})
5 .then(results => {
6 console.log(JSON.stringify(results));
7 console.log(results.length);
8 })
9 .catch(err => console.error(err))

The following example performs the same distinct() call, this time within a transaction. We are using the optional options parameter to pass in the current transaction's session object:

1const client ="mongodb-atlas");
2const session = client.startSession();
5const taskCollection = client.db("tracker").collection("tasks");
7taskCollection.distinct("status", {}, { session })
8 .then(results => {
9 console.log(JSON.stringify(results));
10 console.log(results.length);
11 })
12 .catch(err => console.error(err))
14await session.commitTransaction();

The collection.distinct() action has the following form:

distinct(key, query, options)

The function has the following parameters:

keyRequired. The name of the field in the document in which to find distinct values.
queryRequired. A query for filtering the set of documents before the distinct filter is applied.
optionsOptional. If calling distinct() within a transaction, include the ClientSession object here.

The collection.distinct() action returns a Promise that resolves to an array of distinct values.

Info With Circle IconCreated with Sketch.Note

To learn more, see distinct() in the MongoDB Node.js driver docs.

Give Feedback