Navigation

collection.distinct()

collection.distinct()

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 = context.services.get("mongodb-atlas")
2 .db("tracker").collection("tasks");
3
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 = context.services.get("mongodb-atlas");
2const session = client.startSession();
3session.startTransaction();
4
5const taskCollection = client.db("tracker").collection("tasks");
6
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))
13
14await session.commitTransaction();
15session.endSession();

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

distinct(key, query, options)

The function has the following parameters:

Parameter
Description
key
Required. The name of the field in the document in which to find distinct values.
query
Required. A query for filtering the set of documents before the distinct filter is applied.
options
Optional. 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.

Note

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

Give Feedback