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

检索不同字段值

在本指南中,您可以学习了解如何使用Rust驱动程序检索集合中指定字段的不同值。

在集合中,文档中的单个字段可能包含不同的值。示例,restaurants集合中一个文档的borough 值为 "Manhattan",而另一文档的 borough 值为 "Queens"。您可以使用Rust驱动程序检索值 "Manhattan""Queens" 以及 restaurants集合中所有文档的 borough字段中的所有其他唯一值。

The examples in this guide use the restaurants collection in the sample_restaurants database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.

您可以将 restaurants集合中的文档作为 Document 类型或自定义数据类型的实例访问权限。要指定表示集合数据的数据类型,请将 <T> 类型参数替换为以下值之一:

  • <Document>:将集合文档表示为BSON文档

  • <Restaurant>:将集合文档表示为 Restaurant 结构的实例,在代码示例中进行了定义

要检索指定字段的非重复值,请对 Collection实例调用 distinct() 方法,并传递要查找其非重复值的字段的名称。

distinct() 方法将不同值的列表作为 Vec<Bson> 对象,Bson 值的向量返回。

以下示例检索 restaurants集合中 borough字段的非重复值。

选择AsynchronousSynchronous标签页,查看每个运行时的相应代码:

let boroughs = my_coll.distinct("borough", None).await?;
println!("List of field values for 'borough':");
for b in boroughs {
println!("{:?}", b);
}
List of field values for 'borough':
String("Bronx")
String("Brooklyn")
String("Manhattan")
String("Missing")
String("Queens")
String("Staten Island")
let boroughs = my_coll.distinct("borough", None).run()?;
println!("List of field values for 'borough':");
for b in boroughs {
println!("{:?}", b);
}
List of field values for 'borough':
String("Bronx")
String("Brooklyn")
String("Manhattan")
String("Missing")
String("Queens")
String("Staten Island")

该操作返回一个向量,用于存储每个不同的 borough字段值。尽管多个文档在 borough字段中具有相同的值,但每个值仅在结果中出现一次。

您可以为 distinct() 方法提供查询筛选条件,以查找集合中文档子集的不同字段值。查询筛选条件是一个表达式,用于指定在操作中匹配文档的搜索条件。示例,您可以使用 distinct() 方法仅从匹配文档的子集中查找不同的字段值。

提示

要学习;了解有关创建查询过滤的更多信息,请参阅“指定查询”指南。

以下示例检索 cuisine字段值为 "Turkish" 的所有文档的 borough字段的非重复值。

选择AsynchronousSynchronous标签页,查看每个运行时的相应代码:

let filter = doc! { "cuisine": "Turkish" };
let boroughs = my_coll.distinct("borough", filter).await?;
println!("List of field values for 'borough':");
for b in boroughs {
println!("{:?}", b);
}
List of field values for 'borough':
String("Brooklyn")
String("Manhattan")
String("Queens")
String("Staten Island")
let filter = doc! { "cuisine": "Turkish" };
let boroughs = my_coll.distinct("borough", filter).run()?;
println!("List of field values for 'borough':");
for b in boroughs {
println!("{:?}", b);
}
List of field values for 'borough':
String("Brooklyn")
String("Manhattan")
String("Queens")
String("Staten Island")

您可以修改 distinct() 方法的行为,方法是在 awaitrun() 方法调用之前,将一个或多个选项方法链接到 count_documents() 调用。下表描述了可用于设立去重操作的选项:

选项
说明

collation()

用于操作的排序规则。
类型Collation

hint()

用于操作的索引。
类型Hint

comment()

要添加到操作的注释。
类型Bson

max_time()

操作可以运行的最长时间。
类型Duration

read_concern()

用于操作的读关注(read concern)。
类型ReadConcern

selection_criteria()

读取偏好(read preference)和用于操作的标签。
类型SelectionCriteria

要学习;了解有关 distinct() 方法的详情,请参阅API文档。