指定返回的字段
概述
在本指南中,您可以学习如何使用 Java Reactive Streams 驱动程序指定从读取操作中返回哪些字段。您可以通过使用 投影(一个指定 MongoDB 从查询返回哪些字段的文档)来选择这些字段。
示例数据
本指南中的示例使用sample_restaurants.restaurants
集合,该集合来自Atlas 示例数据集。要了解如何创建免费的 MongoDB Atlas 集群并加载示例数据集,请参阅入门指南。入门指南。
重要
Project Reactor 库
本指南使用Project Reactor库来消费由Java反应式流驱动方法返回的Publisher
实例。要了解有关Project Reactor库及其使用方法,请参阅Reactor文档中的入门。要了解本指南中如何使用Project Reactor库方法,请参阅将数据写入MongoDB指南。
投影类型
您可以使用投影来指定要包含和排除在检索到的文档中的字段。默认情况下,包含某些字段会排除所有其他字段,因此您不能在单个投影中组合包含和排除语句,除非您要从结果中排除_id
字段。
指定要包含的字段
使用以下语法指定要包含在读取操作结果中的字段
projection(fields(include("<field name>")))
要使用投影,请将查询过滤器传递给find()
方法。然后,将projection()
方法链接到find()
方法调用。
以下示例使用find()
方法检索字段值为"Emerald Pub"
的文档。然后,它使用投影只包含返回文档中的name
、cuisine
和borough
字段。
FindPublisher<Document> findProjectionPublisher = restaurants.find( eq("name", "Emerald Pub")) .projection(fields(include("name", "cuisine", "borough"))); Flux.from(findProjectionPublisher) .doOnNext(System.out::println) .blockLast();
{'_id': ObjectId('...'), 'borough': 'Manhattan', 'cuisine': 'American', 'name': 'Emerald Pub'} {'_id': ObjectId('...'), 'borough': 'Queens', 'cuisine': 'American', 'name': 'Emerald Pub'}
当您使用投影来指定要包含在返回文档中的字段时,默认情况下还会包含_id
字段。所有其他字段都默认排除。您必须明确排除_id字段才能将其从返回文档中省略。
排除_id字段
您可以使用excludeId()
方法从返回文档中排除_id
字段。
以下示例执行与上一个示例相同的查询,但还在返回的文档中排除了_id
字段。
FindPublisher<Document> findProjectionPublisher = restaurants.find( eq("name", "Emerald Pub")) .projection(fields(include("name", "cuisine", "borough"), excludeId())); Flux.from(findProjectionPublisher) .doOnNext(System.out::println) .blockLast();
{'borough': 'Manhattan', 'cuisine': 'American', 'name': 'Emerald Pub'} {'borough': 'Queens', 'cuisine': 'American', 'name': 'Emerald Pub'}
指定要排除的字段
使用以下语法指定要从读取操作的结果中排除的字段
projection(fields(exclude("<field name>")))
要使用投影,请将查询过滤器传递给find()
方法。然后,将projection()
方法链接到find()
方法调用。
以下示例使用find()
方法查找所有名称字段值为"Emerald Pub"
的餐厅。然后,它使用投影从返回文档中排除grades
和address
字段。
FindPublisher<Document> findProjectionPublisher = restaurants.find( eq("name", "Emerald Pub")) .projection(fields(exclude("grades", "address"))); Flux.from(findProjectionPublisher) .doOnNext(System.out::println) .blockLast();
{'_id': ObjectId('...'), 'borough': 'Manhattan', 'cuisine': 'American', 'name': 'Emerald Pub', 'restaurant_id': '40367329'} {'_id': ObjectId('...'), 'borough': 'Queens', 'cuisine': 'American', 'name': 'Emerald Pub', 'restaurant_id': '40668598'}
当您使用投影来指定要排除的字段时,任何未指定的字段都会默认包含在返回文档中。
投影错误
以下部分描述了使用投影时可能遇到的一个错误。
包含和排除错误
如果您尝试在单个投影中包含和排除字段,驱动程序将返回以下内容
OperationFailure: ... Cannot Do Exclusion on Field <field> in Inclusion Projection
为了解决这个问题,请确保您的投影仅指定要包含的字段或仅指定要排除的字段。
更多信息
要了解更多关于投影的信息,请参阅MongoDB服务器手册中的投影字段指南。
API 文档
要了解本指南中讨论的任何方法或类型,请参阅以下 API 文档