文档菜单
文档首页
/ / /
Node.js 驱动
/ / /

检索唯一值

本页内容

  • 概述
  • 示例文档
  • 唯一
  • 文档字段参数
  • 示例
  • 查询参数
  • 选项参数
  • 更多信息
  • API 文档

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

要遵循本指南中的示例,请使用以下代码片段将描述餐厅的文档插入到 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" },
]);

注意

您的查询操作可能返回包含匹配文档的游标引用。要了解如何检查游标中存储的数据,请参阅游标基础页面.

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" ]

有关检索不同值的可运行示例,请参阅 检索字段的不同值。

要了解更多关于 distinct() 方法及其参数的信息,您可以访问API 文档.

返回

从游标访问数据