Overview概述
Use the 使用distinct() method to retrieve all distinct values for a specified field across a collection.distinct()方法检索集合中指定字段的所有不同值。
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:myDB.restaurants集合中:
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:distinct()方法需要一个文档字段作为参数。您可以指定以下可选参数来调整方法输出:
A用于优化结果的queryparameter to refine your resultsquery参数An用于设置排序规则的optionsparameter to set collation rulesoptions参数
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:"Queens"(皇后区)和"Manhattan"(曼哈顿区)的数值在样本文件中都出现了多次。但是,以下示例检索了borough字段的唯一值:
// specify "borough" as the field to return values for指定“borough”作为返回值的字段
const cursor = myColl.distinct("borough");
for await (const doc of cursor) {
console.dir(doc);
}
This code outputs the following 此代码输出以下borough values:borough(行政区)值:
[ "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":cuisine(美食)字段的不同值,但不包括"Brooklyn"(布鲁克林)的餐厅:
// exclude Brooklyn restaurants from the output将布鲁克林餐厅排除在输出之外
const query = { borough: { $ne: "Brooklyn" }};
// find the filtered distinct values of "cuisine"找到“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:"Brooklyn"之外的每个行政区值。这会阻止distinct()输出一个cuisine值"Middle Eastern"。代码输出以下值:
[ "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.collation字段定义为options参数来为distinct()方法指定排序规则。此字段允许您设置字符串排序和比较的区域规则。
See the Collation section of the Configure CRUD Operations guide for instructions on applying collations.有关应用排序规则的说明,请参阅配置CRUD操作指南的排序规则部分。
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 {}.options参数时,还必须指定query参数。如果不想使用查询筛选器,请将查询定义为{}。
Example示例
The following example uses a 以下示例在输出不同的collation field to specify German language ordering conventions when outputting the distinct restaurant values:restaurant值时使用collation字段指定德语排序约定:
// 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:在这种情况下,德语字符串排序约定将以“Ä”开头的单词放在以“B”开头的词之前。代码输出以下内容:
[ "Ä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:collation字段,则输出顺序将遵循默认的二进制排序规则。这些规则将以“Ä”开头的单词放在那些首字母没有重音的单词之后:
[ "Borgatti's", "Samba Kitchen", "Tanoreen", "Via Carota", "White Bear", "Äpfel" ]distinct() Example: Full Filedistinct()示例:完整文件
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. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the 此示例还使用Atlas示例数据集中包含的movies collection in the sample_mflix database included in the Atlas sample datasets. sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。
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.movies集合中检索year文档字段的不同值列表。它使用查询文档来匹配director(导演)数组中包含"Barbara Streisand"(芭芭拉·史翠珊)的电影。
JavaScript
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.将uri字符串替换为MongoDB部署的连接字符串。
const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() {
try {
// Get the database and collection on which to run the operation获取要在其上运行操作的数据库和集合
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Specify the document field to find distinct values for指定文档字段以查找不同的值
const fieldName = "year";
// Specify an optional query document to narrow results指定一个可选的查询文档以缩小结果范围
const query = { directors: "Barbra Streisand" };
// Execute the distinct operation执行独特的操作
const distinctValues = await movies.distinct(fieldName, query);
// Print the result打印结果
console.log(distinctValues);
} finally {
await client.close();
}
}
run().catch(console.dir);TypeScript
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.将uri字符串替换为MongoDB部署的连接字符串。
const uri = "<connection string uri>";
const client = new MongoClient(uri);
interface Movie {
directors: string;
year: number;
}
async function run() {
try {
// define a database and collection on which to run the method定义要在其上运行该方法的数据库和集合
const database = client.db("sample_mflix");
const movies = database.collection<Movie>("movies");
const distinctValues = await movies.distinct("year", {
directors: "Barbra Streisand",
});
console.log(distinctValues);
} finally {
await client.close();
}
}
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:要了解有关本指南中讨论的任何类型或方法的更多信息,请参阅以下API文档: