对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
MongoDB Branding Shape
Click here >
Docs 菜单

检索不同字段值

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

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

restaurantssample_restaurants本指南中的示例使用Atlas示例数据集的 数据库中的 集合。要从Scala应用程序访问权限此集合,请创建一个连接到Atlas 集群的MongoClient,并将以下值分配给 databasecollection 变量:

val database: MongoDatabase = client.getDatabase("sample_restaurants")
val collection: MongoCollection[Document] = database.getCollection("restaurants")

要学习如何创建免费的MongoDB Atlas 集群并加载示例数据集,请参阅MongoDB 入门指南

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

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

collection.distinct("borough")
.subscribe((value: String) => println(value),
(e: Throwable) => println(s"There was an error: $e"))
Bronx
Brooklyn
Manhattan
Missing
Queens
Staten Island

该操作会返回一个 DistinctObservable 类的实例,您可以遍历该实例以访问权限每个不同的 borough字段值。 尽管多个文档在 borough字段中具有相同的值,但每个值仅在结果中出现一次。

您可以为 distinct() 方法提供查询过滤,以查找集合中文档子集中的不同字段值。查询过滤是一个表达式,用于指定在操作中匹配文档的搜索条件。有关创建查询过滤的更多信息,请参阅“指定查询”指南。

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

val filter = equal("cuisine", "Italian")
collection.distinct("borough", filter)
.subscribe((value: String) => println(value),
(e: Throwable) => println(s"There was an error: $e"))
Bronx
Brooklyn
Manhattan
Queens
Staten Island

您可以通过链接 DistinctObservable 类提供的方法来修改 distinct() 方法的行为。 下表描述了其中一些方法:

方法
说明

collation()


设置用于操作的排序规则。参数类型:Collation

comment()


为操作附加注释。参数类型:BsonValueString

first()

仅检索第一个非重复字段值。

以下示例检索 borough字段值为 "Bronx"cuisine字段值为 "Pizza" 的所有文档的 name字段的非重复值。 然后,它将 comment() 方法链接到 distinct(),为操作添加注释:

val filter = and(equal("borough", "Bronx"), equal("cuisine", "Pizza"))
collection.distinct("name", filter)
.comment("Bronx Pizza restaurants")
.subscribe((value: String) => println(value),
(e: Throwable) => println(s"There was an error: $e"))
$1.25 Pizza
18 East Gunhill Pizza
2 Bros
Aenos Pizza
Alitalia Pizza Restaurant
Amici Pizza And Pasta
Angie'S Cafe Pizza
...

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: