Overview
在本指南中,您可以学习如何使用Ruby驱动程序通过投影来指定从读取操作中返回哪些字段。投影是指定MongoDB从查询中返回哪些字段的文档。
样本数据
The examples in this guide use the restaurants collection in the sample_restaurants database from the Atlas sample datasets. To access this collection from your Ruby application, create a Mongo::Client object that connects to an Atlas cluster and assign the following values to your database and collection variables:
database = client.use('sample_restaurants') collection = database[:restaurants]
要学习如何创建免费的MongoDB Atlas 集群并加载示例数据集,请参阅MongoDB 入门指南。
投影类型
您可以使用投影来指定要在返回文档中包含或排除哪些字段。除非要排除 _id字段,否则不能在单个投影中组合包含和排除语句。
指定要包含的字段
要在读取操作结果中包含特定字段,请在 find 方法的参数中指定 projection 选项。要设立此选项,请使用以下语法:
{ projection: { <field_name>: 1 } }
以下示例使用 find 方法查找 name字段值为 'Emerald Pub' 的所有餐厅。然后,代码指定 projection 选项,指示查找操作仅返回匹配文档的 name、cuisine 和 borough 字段:
opts = { projection: { name: 1, cuisine: 1, borough: 1 } } collection.find({ name: 'Emerald Pub' }, opts).each do |doc| puts doc end
When you use a projection to specify fields to include in the return document, the _id field is also included by default. All other fields are implicitly excluded. To remove the _id field from the return document, you must explicitly exclude it.
排除 _id 字段
在指定要包含的字段时,您还可以从返回的文档中排除_id字段。
以下示例执行与上一示例相同的查询,但从投影中排除_id字段:
opts = { projection: { name: 1, cuisine: 1, borough: 1, _id: 0 } } collection.find({ name: 'Emerald Pub' }, opts).each do |doc| puts doc end
指定要排除的字段
要从读取操作结果中排除特定字段,请在 find 方法的参数中指定 projection 选项。要设立此选项,请使用以下语法:
{ projection: { <field_name>: 0 } }
以下示例使用 find 方法查找 name字段值为 'Emerald Pub' 的所有餐厅。然后,代码使用 projection 选项指示查找操作省略结果中的 grades 和 address 字段:
opts = { projection: { grades: 0, address: 0 } } collection.find({ name: 'Emerald Pub' }, opts).each do |doc| puts doc end
当您使用投影指定要排除的字段时,任何未指定的字段都将隐式包含在返回文档中。
更多信息
To learn more about projections, see the Project Fields guide in the MongoDB Server manual.
API 文档
To learn more about the find method, see the API documentation.