Retrieve Distinct Values
On this page
Overview
Use the distinct()
method to retrieve all distinct values for a specified field
across a collection.
Sample Documents
To follow the examples in this guide, use the following code snippet to insert documents
that describe restaurants into the myDB.restaurants
collection:
const myDB = client.db("myDB"); const myColl = myDB.collection("restaurants"); await myColl.insertMany([ { "_id": 1, "restaurant": "White Bear", "borough": "Queens", "cuisine": "Chinese" }, { "_id": 2, "restaurant": "Via Carota", "borough": "Manhattan", "cuisine": "Italian" }, { "_id": 3, "restaurant": "Borgatti's", "borough": "Bronx", "cuisine": "Italian" }, { "_id": 4, "restaurant": "Tanoreen", "borough": "Brooklyn", "cuisine": "Middle Eastern" }, { "_id": 5, "restaurant": "Äpfel", "borough": "Queens", "cuisine": "German" }, { "_id": 6, "restaurant": "Samba Kitchen", "borough": "Manhattan", "cuisine": "Brazilian" }, ]);
Note
Your query operation may return a reference to a cursor that contains matching documents. To learn how to examine data stored in the cursor, see the Access Data From a Cursor page.
Distinct
The distinct()
method requires a document field as a parameter. You can specify the
following optional parameters to adjust the method output:
A
query
parameter to refine your resultsAn
options
parameter to set collation rules
Document Field Parameter
Pass the name of the document field to return a list of the field's unique values.
Example
The "Queens"
and "Manhattan"
borough values each appear more than
once in the sample documents. However, the following example retrieves the
unique values of the borough
field:
// specify "borough" as the field to return values for const cursor = myColl.distinct("borough"); for await (const doc of cursor) { console.dir(doc); }
This code outputs the following borough
values:
[ "Bronx", "Brooklyn", "Manhattan", "Queens" ]
Query Parameter
You can specify a query parameter to return unique values for documents that match your query.
Visit Specify a Query for more information on constructing a query filter.
Example
The following example outputs the distinct values of the cuisine
field but
excludes restaurants in "Brooklyn"
:
// exclude Brooklyn restaurants from the output const query = { borough: { $ne: "Brooklyn" }}; // find the filtered distinct values of "cuisine" const cursor = myColl.distinct("cuisine", query); for await (const doc of cursor) { console.dir(doc); }
In this case, the query filter matches every borough value except for "Brooklyn"
. This
prevents distinct()
from outputting one cuisine
value, "Middle Eastern"
.
The code outputs the following values:
[ "Brazilian", "Chinese", "German", "Italian" ]
Options Parameter
You can specify the collation to the distinct()
method by defining a
collation
field as an options
parameter. This field allows you to set
regional rules for string ordering and comparisons.
See the Collation section of the Configure CRUD Operations guide for instructions on applying collations.
Note
When using the options
parameter, you must also specify a query
parameter. If
you don't want to use a query filter, define the query as {}
.
Example
The following example uses a collation
field to specify German language ordering
conventions when outputting the distinct restaurant
values:
// define an empty query document const query = {}; // specify German string ordering conventions const options = { collation: { locale: "de" }}; const cursor = myColl.distinct("restaurant", query, options); for await (const doc of cursor) { console.dir(doc); }
In this case, German string ordering conventions place words beginning with "Ä" before those beginning with "B". The code outputs the following:
[ "Äpfel", "Borgatti's", "Samba Kitchen", "Tanoreen", "Via Carota", "White Bear" ]
If you do not specify the collation
field, the output order follows default
binary collation rules. These rules place words beginning with "Ä" after the those
with unaccented first letters:
[ "Borgatti's", "Samba Kitchen", "Tanoreen", "Via Carota", "White Bear", "Äpfel" ]
distinct() Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a
connection URI. To learn more about connecting to your MongoDB
instance, see the Connect to MongoDB guide. This example
also uses the movies
collection in the sample_mflix
database
included in the Atlas sample datasets. You
can load them into your database on the free tier of MongoDB Atlas by
following the Get Started with Atlas Guide.
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"
in the director
array.
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 11 // Get the database and collection on which to run the operation 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Specify the document field to find distinct values for 16 const fieldName = "year"; 17 18 // Specify an optional query document to narrow results 19 const query = { directors: "Barbra Streisand" }; 20 21 // Execute the distinct operation 22 const distinctValues = await movies.distinct(fieldName, query); 23 24 // Print the result 25 console.log(distinctValues); 26 } finally { 27 await client.close(); 28 } 29 } 30 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Movie { 9 directors: string; 10 year: number; 11 } 12 13 async function run() { 14 try { 15 // define a database and collection on which to run the method 16 const database = client.db("sample_mflix"); 17 const movies = database.collection<Movie>("movies"); 18 19 const distinctValues = await movies.distinct("year", { 20 directors: "Barbra Streisand", 21 }); 22 23 console.log(distinctValues); 24 } finally { 25 await client.close(); 26 } 27 } 28 run().catch(console.dir);
Running the preceding example, results in the following output:
[ 1983, 1991, 1996 ]
API Documentation
To learn more about any of the types or methods discussed in this guide, see the following API documentation: