检索不同字段值
Overview
在本指南中,您可以学习;了解如何使用Scala驾驶员检索集合中指定字段的不同值。
在集合中,不同文档的单个字段可能包含不同值。示例,restaurants
集合中一个文档的borough
值为 "Manhattan"
,而另一文档的 borough
值为 "Queens"
。通过使用Scala驾驶员,您可以检索集合中多个文档中某个字段包含的所有唯一值。
样本数据
本指南中的示例使用restaurants
sample_restaurants
Atlas示例数据集的 数据库中的 集合。要从Scala应用程序访问权限此集合,请创建一个连接到AtlasMongoClient
集群的database
,然后为 和collection
变量分配以下值:
val database: MongoDatabase = client.getDatabase("sample_restaurants") val collection: MongoCollection[Document] = database.getCollection("restaurants")
要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。
Retrieve Distinct Values
要检索指定字段的非重复值,请调用 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()
方法的行为。下表描述了其中一些方法:
方法 | 说明 |
---|---|
| Sets the collation to use for the operation. Parameter Type: Collation |
| Sets the maximum amount of time that the operation can run. Parameter Type: Duration |
| Attaches a comment to the operation. Parameter Type: BsonValue or String |
| Retrieves only the first distinct field value. |
以下示例检索 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 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: