Retrieve Data
Overview
在本指南中,您可以学习;了解如何使用MongoDB Java Reactive Streams 驱动程序通过读取操作从MongoDB集合中检索数据。
样本数据
本指南中的示例使用 Atlas示例数据集中的 sample_restaurants.restaurants
集合。 要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅入门。
重要
项目 Reactor 库
本指南使用 Project Reactor 库来使用Java Reactive Streams驾驶员方法返回的 Publisher
实例。 要学习;了解有关 Project Reactor 库及其使用方法的更多信息,请参阅 Reactor 文档中的“入门” 。要进一步学习;了解如何使用本指南中的 Project Reactor 库方法,请参阅“将数据写入MongoDB”指南。
查找文档
Java Reactive Streams驾驶员包含一种从集合中检索文档的方法: find()
。
此方法采用查询过滤并返回一个或多个匹配的文档。 查询过滤是一个对象,用于指定要在查询中检索的文档。
如需学习;了解有关查询筛选器的更多信息,请参阅“指定查询”指南。
查找一个文档
要查找集合中的单个文档,请将first()
方法链接到find()
方法调用,并将查询过滤传递给指定要查找的文档条件的find()
方法调用。 如果有多个文档与查询过滤匹配,则find().first()
构造会从检索到的结果中返回第一个匹配的文档。 如果没有文档与查询过滤匹配,则该构造返回None
。
提示
当您知道只有一个匹配文档或者您只对第一个匹配项感兴趣时, find().first()
构造非常有用。
以下示例使用find().first()
构造查找"cuisine"
字段值为"Bakery"
的第一个文档:
Publisher<Document> findDocPublisher = restaurants.find( eq("cuisine", "Bakery")).first(); Mono.from(findDocPublisher) .doOnNext(System.out::println) .blockLast();
要学习;了解有关排序的更多信息,请参阅《指定要返回的文档》指南。
查找多个文档
要查找集合中的多个文档,请将查询筛选器传递给 find()
方法,其中指定要检索的文档条件。
以下示例使用find()
方法查找"cuisine"
字段值为"Spanish"
的所有文档:
FindPublisher<Document> findDocPublisher = restaurants.find( eq("cuisine", "Spanish")); Flux.from(findDocPublisher) .doOnNext(System.out::println) .blockLast();
注意
查找所有文档
要查找集合中的所有文档,请不要向find()
方法传递任何参数:
Publisher<Document> findAllPublisher = restaurants.find(); Flux.from(findAllPublisher) .doOnNext(System.out::println) .blockLast();
修改查找行为
您可以通过将其他方法链接到find()
方法来修改该方法的行为。 下表描述了常用的方法:
Argument | 说明 |
---|---|
| The maximum number of documents within each batch returned in a query result. By default, the find
command has an initial batch size of 101 documents and a maximum size of 16 mebibytes (MiB)
for each subsequent batch. This option can enforce a smaller limit than 16 MiB, but not a larger
one. If you set batchSize to a limit that results in batches larger than
16 MiB, this option has no effect.A batchSize of 0 means that the cursor will be established, but no documents
will be returned in the first batch. |
| Sets the collation options as an instance of the Collation class. |
| Attaches a string to the query. This can help you trace and interpret the
operation in the server logs and in profile data. To learn more about query comments,
see the cursor.comment() page in
the MongoDB Server manual. |
| Gets or sets the index to scan for documents.
For more information, see the hint statement
in the MongoDB Server manual. |
以下示例使用 find()
方法查找 "cuisine"
字段值为 "Italian"
并设置注释的所有文档:
FindPublisher<Document> findDocPublisher = restaurants.find( eq("cuisine", "Italian")).comment("Find operation"); Flux.from(findDocPublisher) .doOnNext(System.out::println) .blockLast();
有关可用参数的完整列表,请参阅 API文档 用于FindPublisher
接口。
更多信息
如需学习;了解有关查询筛选器的更多信息,请参阅“指定查询”指南。
有关使用Java Reactive Streams驾驶员检索文档的可运行代码示例,请参阅读取数据指南。
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: