Overview
使用 distinct()
方法检索集合中指定字段的所有不同值。
示例文档
要遵循本指南中的示例,请使用以下代码片段将描述餐厅的文档插入到myDB.restaurants
collection中:
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
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() 示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。此示例还使用movies
sample_mflix
Atlas示例数据集包含的 数据库中的 集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
以下代码片段从 movies
集合中检索 year
文档字段的非重复值列表。它使用查询文档来匹配 director
大量中包含 "Barbara Streisand"
的电影。
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 30 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Movie { 9 directors: string; 10 year: number; 11 } 12 13 async 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 } 28 run().catch(console.dir);
运行前面的示例会产生以下输出:
[ 1983, 1991, 1996 ]
API 文档
要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档: