Docs 菜单
Docs 主页
/ /

Retrieve Distinct Values

使用 distinct()方法检索集合中指定字段的所有不同值。

要遵循本指南中的示例,请使用以下代码片段将描述餐厅的文档插入到myDB.restaurantscollection中:

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" },
]);

注意

您的查询操作可能会返回对包含匹配文档的游标的引用。要学习;了解如何检查存储在游标中的数据,请参阅从游标访问数据页面。

distinct()方法需要一个文档字段作为参数。 您可以指定以下可选参数来调整方法输出:

  • 用于优化结果的query参数

  • 用于设置排序规则的options参数

传递文档字段的名称以返回该字段的唯一值的列表。

"Queens""Manhattan"行政区值在样本文档中均出现多次。 但是,以下示例将检索borough字段的唯一值:

// specify "borough" as the field to return values for
const cursor = myColl.distinct("borough");
for await (const doc of cursor) {
console.dir(doc);
}

此代码输出以下borough值:

[ "Bronx", "Brooklyn", "Manhattan", "Queens" ]

您可以指定查询参数,为与查询匹配的文档返回唯一值。

有关构建查询过滤器的更多信息,请访问指定一个查询

以下示例输出cuisine字段的不同值,但不包括"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);
}

在这种情况下,查询筛选器匹配除"Brooklyn"之外的每个行政区值。 这会防止distinct()输出一个cuisine"Middle Eastern" 。 该代码输出以下值:

[ "Brazilian", "Chinese", "German", "Italian" ]

您可以通过将collation字段定义为options参数来指定distinct()方法的排序规则。 此字段允许您设置字符串排序和比较的区域规则。

有关应用排序规则的说明,请参阅 配置增删改查操作 指南的 排序规则 部分。

注意

使用options参数时,您还必须指定query参数。 如果不想使用查询筛选器,请将查询定义为{}

以下示例使用collation字段在输出不同的restaurant值时指定德语排序约定:

// 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);
}

在这种情况下,德语字符串排序约定会将以“?”开头的单词放在以“B”开头的单词之前。 该代码输出以下内容:

[ "Äpfel", "Borgatti's", "Samba Kitchen", "Tanoreen", "Via Carota", "White Bear" ]

如果不指定collation字段,输出顺序将遵循默认的二进制排序规则规则。这些规则将以 "?" 开头的单词放在首字母不带重音的单词之后:

[ "Borgatti's", "Samba Kitchen", "Tanoreen", "Via Carota", "White Bear", "Äpfel" ]

注意

设置示例

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 MongoDB Get Started.

以下代码片段从 movies集合中检索 year文档字段的非重复值列表。它使用查询文档来匹配 director大量中包含 "Barbara Streisand" 的电影。

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async 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}
30run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 directors: string;
10 year: number;
11}
12
13async 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}
28run().catch(console.dir);

运行前面的示例会产生以下输出:

[ 1983, 1991, 1996 ]

要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档:

后退

计算文档

在此页面上