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

检索字段的唯一值

您可以通过使用来检索集合中字段的唯一值列表。collection.distinct() 方法。调用distinct() 方法,在 Collection 对象上传递一个文档字段名参数作为 String,以生成一个包含在指定文档字段中找到的不同值的列表,如下所示

const distinctValues = myColl.distinct("countries", query);

您可以使用 点表示法 指定 嵌套文档 中的文档字段。如果您在包含数组的文档字段上调用 distinct(),则方法将每个元素视为单独的值。请参阅以下示例,该示例演示了在 awards 子文档中的 wins 字段上调用该方法

const distinctValues = myColl.distinct("awards.wins", query);

您可以使用 options 对象作为 distinct() 方法的第三个参数来指定更多查询选项。有关查询参数的详细信息,请参阅 API 文档中的 distinct() 方法。

如果您指定的文档字段名值不是 String 类型,例如 DocumentArrayNumbernull,则方法不执行并返回一个类似于以下消息的 TypeMismatch 错误

"key" 类型错误。期望字符串,但找到的是非字符串类型。

访问检索不同值以获取关于distinct()方法的更多信息。

以下代码片段从movies集合中检索了year文档字段的唯一值列表。它使用查询文档来匹配包含"Barbara Streisand"作为director的电影。

注意

您可以使用此示例连接到MongoDB的一个实例并与之交互,以包含样本数据的数据库。要了解更多关于连接到您的MongoDB实例和加载数据集的信息,请参阅使用示例指南。

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 ]

返回

文档计数