文档首页 → 开发应用程序 → Python 驱动程序 → PyMongo
指定要返回的字段
概述
在本指南中,您可以了解如何通过使用 投影 来指定从读取操作返回哪些字段。投影是一个文档,它指定MongoDB从查询返回哪些字段。
示例数据
本指南中的示例使用来自sample_restaurants.restaurants
集合的Atlas 示例数据集。要了解如何创建免费的MongoDB Atlas集群并加载数据集,请参阅开始使用PyMongo指南。
投影类型
您可以使用投影来指定要包含在返回文档中的字段,或指定要排除的字段。除非您正在排除 _id
字段,否则您不能在单个投影中组合包含和排除语句。
指定要包含的字段
使用以下语法指定要包含在结果中的字段
{ "<Field Name>": 1 }
以下示例使用 find()
方法查找所有具有 name
字段值为 "Emerald Pub"
的餐厅。然后使用投影只返回返回文档中的 name
、cuisine
和 borough
字段。
results = restaurants.find({ "name" : "Emerald Pub"}, {"name": 1, "cuisine": 1, "borough": 1}) for restaurant in results: print(restaurant)
{'_id': ObjectId('...'), 'borough': 'Manhattan', 'cuisine': 'American', 'name': 'Emerald Pub'} {'_id': ObjectId('...'), 'borough': 'Queens', 'cuisine': 'American', 'name': 'Emerald Pub'}
当您使用投影来指定返回文档中要包含的字段时,默认情况下也会包含_id
字段。所有其他字段都将被隐式排除。要从不返回文档中移除_id
字段,您必须显式排除它。
排除_id
字段
在指定要包含的字段时,您还可以从返回的文档中排除_id
字段。
以下示例执行与上一个示例相同的查询,但排除了投影中的_id
字段
results = restaurants.find({ "name" : "Emerald Pub"}, {"_id": 0, "name": 1, "cuisine": 1, "borough": 1}) for restaurant in results: print(restaurant)
{'borough': 'Manhattan', 'cuisine': 'American', 'name': 'Emerald Pub'} {'borough': 'Queens', 'cuisine': 'American', 'name': 'Emerald Pub'}
指定要排除的字段
使用以下语法来指定要从结果中排除的字段
{ "<Field Name>": 0 }
以下示例使用find()
方法查找所有名称字段值为"Emerald Pub"
的餐厅。然后它使用投影来排除返回文档中的grades
和address
字段
results = restaurants.find({ "name" : "Emerald Pub"}, {"grades": 0, "address": 0} ) for restaurant in results: print(restaurant)
{'_id': ObjectId('...'), 'borough': 'Manhattan', 'cuisine': 'American', 'name': 'Emerald Pub', 'restaurant_id': '40367329'} {'_id': ObjectId('...'), 'borough': 'Queens', 'cuisine': 'American', 'name': 'Emerald Pub', 'restaurant_id': '40668598'}
当您使用投影来指定要排除的字段时,任何未指定的字段都将隐式包含在返回文档中。
故障排除
以下部分描述了使用投影时可能会遇到的错误。
在包含投影中不能排除字段<field>
如果尝试在单个投影中包含和排除字段,驱动程序将返回带有此消息的OperationFailure
。请确保您的投影仅指定要包含的字段或要排除的字段。
更多信息
有关投影的更多信息,请参阅MongoDB服务器手册中的投影字段指南。
API文档
有关本指南中讨论的任何方法或类型的更多信息,请参阅以下API文档