对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

指定要返回的字段

在本指南中,您可以了解如何使用投影指定从读取操作中返回哪些字段。 投影是指定 MongoDB 从查询中返回哪些字段的文档。

本指南中的示例使用来自 Atlas 示例数据集的 sample_restaurants 数据库中的 restaurants 集合。要了解如何创建免费的 MongoDB 部署并加载示例数据集,请参阅 MongoDB入门指南。

此集合中的文档由以下Kotlin数据类建模:

data class Restaurant( @BsonId val id: ObjectId? = null, val name: String, val borough: String, val cuisine: String)

您可以使用投影来指定要在返回文档中包含哪些字段,或指定要排除哪些字段。

在指定要包含在投影中的某些字段时,会隐式排除所有其他字段(默认包含的_id字段除外)。 除非要排除_id字段,否则不能在单个投影中组合包含和排除语句。

要从返回的文档删除_id字段,您必须明确将其排除。

使用以下语法指定要包含在结果中的字段:

val projection = Projection.fields( Projections.include(<fieldName1>, <fieldName2>, ...))

以下示例使用find()方法查找name字段值为"Emerald Pub"的所有餐厅。 然后,它使用投影仅返回所返回文档的name 、 cuisine和borough字段。

val projection = Projections.fields( Projections.include( Restaurant::name.name, Restaurant::cuisine.name, Restaurant::borough.name )) val results = collection .find(eq(Restaurant::name.name, "Emerald Pub")) .projection(projection) results.forEach { result -> println(result)}

在指定要包含的字段时,您还可以从返回的文档中排除_id字段。

以下示例运行与上一示例相同的查询,但从投影中排除_id字段:

val projection = Projections.fields( Projections.excludeId(), Projections.include( Restaurant::name.name, Restaurant::cuisine.name, Restaurant::borough.name )) val results = collection .find(eq(Restaurant::name.name, "Emerald Pub")) .projection(projection) results.forEach { result -> println(result)}

要了解有关投影的更多信息,请参阅 MongoDB Server 手册中的项目字段指南。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: