Docs 菜单
Docs 主页
/ / /
Node.js
/ / /

检索非重复值

在此页面上

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

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

Without specifying a collation field, the output order would follow default binary collation rules. 这些规则将以 "?" 开头的单词放在首字母不带重音的单词之后:

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

有关检索非重复值的可运行示例,请参阅检索字段的非重复值。

要了解有关distinct() 方法及其参数的详情,可以访问 API 文档。

后退

从游标访问数据