检索不同的字段值
概述
在一个集合中,不同的文档可能包含单个字段的不同值。例如,在restaurant
集合中有一个文档的 borough
值为 "Manhattan"
,另一个的值为 "Queens"
。使用 Kotlin Sync 驱动程序,您可以检索集合中多个文档包含的字段的所有不同值。
示例数据
本指南中的示例使用 restaurants
集合,该集合来自 sample_restaurants
数据库。Atlas 示例数据集。要了解如何创建免费的 MongoDB Atlas 集群并加载示例数据集,请参阅 Atlas 入门 指南。
以下 Kotlin 数据类模型表示该集合中的文档
data class Restaurant( val name: String, val borough: String, val cuisine: String )
distinct()
方法
要检索指定字段的唯一值,请调用 distinct()
方法,并传入您想要查找唯一值的字段名称。
在集合中检索唯一值
以下示例检索了 restaurants
集合中 borough
字段的唯一值
val results = collection.distinct<String>(Restaurant::borough.name) results.forEach { result -> println(result) }
Bronx Brooklyn Manhattan Missing Queens Staten Island
结果显示了集合中所有文档的 borough
字段中出现的每个唯一值。尽管一些文档在 borough
字段中有相同的值,但每个值在结果中只出现一次。
在指定文档中检索唯一值
您可以为 distinct()
方法提供一个 查询过滤器,以找到集合中一部分文档的唯一字段值。查询过滤器是一个表达式,用于指定用于匹配操作中文档的搜索标准。有关创建查询过滤器的更多信息,请参阅指定查询.
以下示例检索了所有具有 cuisine
字段值为 "Italian"
的文档的 borough
字段的唯一值
val results = collection.distinct<String>( Restaurant::borough.name, eq(Restaurant::cuisine.name, "Italian") ) results.forEach { result -> println(result) }
Bronx Brooklyn Manhattan Queens Staten Island
修改distinct行为
可以通过将方法链接到 distinct()
方法调用来修改 distinct()
方法。如果您没有指定任何选项,驱动程序不会自定义操作。
下表描述了一些您可以用来自定义 distinct()
操作的方法
方法 | 描述 |
---|---|
batchSize() | 设置每批返回的文档数量。 |
collation() | 指定排序结果时要使用的语言排序类型。有关更多信息,请参阅 MongoDB 服务器手册中的 排序。 |
comment() | 指定要附加到操作上的注释。 |
filter() | 设置应用于查询的查询过滤器。 |
forEach() | 对 distinct() 操作返回的每个元素执行给定的操作。 |
maxTime() | 设置允许操作运行的最大时间,单位为毫秒。 |
有关您可以用来修改 distinct()
方法的完整方法列表,请参阅 DistinctIterable API 文档。
以下示例检索具有 borough
字段值为 "Bronx"
和 cuisine
字段值为 "Pizza"
的所有文档的 name
字段的唯一值。它还使用 comment
选项将注释添加到操作中。
val results = collection.distinct<String>( Restaurant::name.name, and( eq(Restaurant::borough.name, "Bronx"), eq(Restaurant::cuisine.name, "Pizza") ) ).comment("Bronx pizza restaurants") results.forEach { result -> println(result) }
$1.25 Pizza 18 East Gunhill Pizza 2 Bros Aenos Pizza Alitalia Pizza Restaurant ...
附加信息
要了解更多关于特定命令的信息,请参阅MongoDB服务器手册中的Distinct指南。
API文档
要了解更多关于本指南中讨论的任何方法或类型的信息,请参阅以下API文档