检索不同的字段值
概述
在一个集合中,不同的文档可能包含同一个字段的不同的值。例如,restaurant
集合中的一个文档有 borough
值为 "Manhattan"
,另一个有 borough
值为 "Queens"
。使用 Java Reactive Streams 驱动程序,您可以检索集合中多个文档中字段的全部不同值。
示例数据
本指南中的示例使用来自Atlas 示例数据集的 sample_restaurants.restaurants
集合。有关创建免费 MongoDB Atlas 集群并加载示例数据集的说明,请参阅入门.
重要
项目反应器库
本指南使用 Project Reactor 库来消费 Java 反应式流驱动方法返回的 Publisher
实例。要了解有关 Project Reactor 库及其使用方法,请参阅 Reactor 文档中的入门。要了解本指南中如何使用 Project Reactor 库方法,请参阅写入 MongoDB 数据指南。
distinct()
方法
要检索指定字段的唯一值,请调用 distinct()
方法并传递要查找唯一值的字段名称。
跨集合检索唯一值
以下示例检索了 restaurants
集合中 borough
字段的唯一值。
DistinctPublisher<String> distinctPublisher = collection .distinct("borough", String.class); Flux.from(distinctPublisher) .doOnNext(System.out::println) .blockLast();
Bronx Brooklyn Manhattan Missing Queens Staten Island
结果显示了集合中所有文档的 borough
字段中出现的每个唯一值。尽管有多个文档在 borough
字段中具有相同的值,但每个值在结果中只出现一次。
从指定文档中检索不同值
您可以为 distinct()
方法提供一个 查询过滤器 来查找集合中子集文档的不同字段值。查询过滤器是一个表达式,用于指定用于匹配操作中文档的搜索条件。有关创建查询过滤器的更多信息,请参阅指定查询。
以下示例检索所有具有 cuisine
字段值为 "Italian"
的文档中 borough
字段的不同值。
Bson filter = Filters.eq("cuisine", "Italian"); DistinctPublisher<String> distinctPublisher = collection .distinct("borough", String.class) .filter(filter); Flux.from(distinctPublisher) .doOnNext(System.out::println) .blockLast();
Bronx Brooklyn Manhattan Queens Staten Island
修改不同行为
可以通过将方法链接到 distinct()
方法调用来修改 distinct()
方法。如果不指定任何选项,驱动程序不会自定义操作。
以下表格描述了一些您可以用于自定义 distinct()
操作的方法
方法 | 描述 |
---|---|
batchSize() | 设置每批返回的文档数。 |
collation() | 指定排序结果时要使用的语言排序类型。有关更多信息,请参阅 MongoDB 服务器手册中的 排序。 |
comment() | 指定要附加到操作上的注释。 |
filter() | 设置应用于查询的查询过滤器。 |
maxTime() | 设置允许操作运行的最大时间,以毫秒为单位。 |
要查看可以用于修改 distinct()
方法的所有方法的完整列表,请参阅 DistinctPublisher API 文档。
以下示例检索所有具有 borough
字段值为 "Bronx"
和 cuisine
字段值为 "Pizza"
的文档中 name
字段的唯一值。它还使用 comment
选项向操作添加注释。
Bson filter = Filters.and( Filters.eq("borough", "Bronx"), Filters.eq("cuisine", "Pizza") ); DistinctPublisher<String> distinctPublisher = collection .distinct("name", String.class) .filter(filter) .comment("Bronx pizza restaurants"); Flux.from(distinctPublisher) .doOnNext(System.out::println) .blockLast();
$1.25 Pizza 18 East Gunhill Pizza 2 Bros Aenos Pizza Alitalia Pizza Restaurant ...
更多信息
要了解更多关于 distinct 命令的信息,请参阅 MongoDB 服务器手册中的 Distinct 指南。
API 文档
要了解更多关于本指南中讨论的任何方法或类型的信息,请参阅以下 API 文档