collection.distinct()¶
Definition¶
collection.distinct()
¶
Return a list of distinct values for the given key within a collection or within a find result set.
Usage¶
Example¶
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:
1 const taskCollection = context.services.get("mongodb-atlas") 2 .db("tracker").collection("tasks"); 3 4 taskCollection.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:
1 const client = context.services.get("mongodb-atlas"); 2 const session = client.startSession(); 3 session.startTransaction(); 4 5 const taskCollection = client.db("tracker").collection("tasks"); 6 7 taskCollection.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 14 await session.commitTransaction(); 15 session.endSession();
Parameters¶
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. |
Return Value¶
The collection.distinct()
action returns a Promise that resolves to an array of
distinct values.
To learn more, see distinct() in the MongoDB Node.js driver docs.