对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

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参数

distinct() 方法会返回 Promise,该 解析为由字段的不同值组成的数组。使用 await 访问独特值数组,如本页上的示例所示。

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

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

// specify "borough" as the field to return values forconst distinctValues = await myColl.distinct("borough");console.log(distinctValues);

此代码输出以下borough值:

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

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

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

以下示例输出cuisine字段的不同值,但不包括"Brooklyn"中的餐馆:

// exclude Brooklyn restaurants from the outputconst query = { borough: { $ne: "Brooklyn" }}; // find the filtered distinct values of "cuisine"const distinctValues = await myColl.distinct("cuisine", query);console.log(distinctValues);

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

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

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

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

注意

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

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

// define an empty query documentconst query = {};// specify German string ordering conventionsconst options = { collation: { locale: "de" }}; const distinctValues = await myColl.distinct("restaurant", query, options);console.log(distinctValues);

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

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

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

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

注意

设置示例

该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接到 MongoDB 指南。本示例还使用了Atlas 示例数据集中包含的 sample_mflix 数据库中的 movies 集合。您可以按照 MongoDB 入门指南,将它们加载到 MongoDB Atlas 的免费集群数据库中。

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

import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string.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);

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

[ 1983, 1991, 1996 ]

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