Docs 菜单
Docs 主页
/ / /
Scala
/

指定要返回的字段

在此页面上

  • Overview
  • 样本数据
  • 投影类型
  • 指定要包含的字段
  • 排除 _id字段
  • 指定要排除的字段
  • 更多信息
  • API 文档

在本指南中,您可以学习;了解如何使用Scala驾驶员通过投影来指定从读取操作中返回哪些字段。投影是指定MongoDB从查询中返回哪些字段的文档。

本指南中的示例使用restaurants sample_restaurantsAtlas示例数据集的 数据库中的 集合。要从Scala应用程序访问权限此集合,请创建一个连接到AtlasMongoClient 集群的 ,并将以下值分配给databasecollection 变量:

val database: MongoDatabase = client.getDatabase("sample_restaurants")
val collection: MongoCollection[Document] = database.getCollection("restaurants")

要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。

您可以使用投影来指定要在返回文档中包含哪些字段,或指定要排除哪些字段。 除非要排除_id字段,否则不能在单个投影中组合包含和排除语句。

要指定结果中包含的字段,请将 projection() 方法链接到 find() 方法。 Projections 类提供了 include() 辅助方法,您可以使用该方法设立要包含的字段。

以下示例使用 find() 方法查找 name字段值为 "Emerald Pub" 的所有餐厅。然后,代码调用 projection()include() 方法,指示查找操作仅返回匹配文档的 namecuisineborough 字段:

collection
.find(equal("name", "Emerald Pub"))
.projection(include("name", "cuisine", "borough"))
.subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"_id": {"$oid": "..."}, "borough": "Manhattan", "cuisine": "American", "name": "Emerald Pub"}
{"_id": {"$oid": "..."}, "borough": "Queens", "cuisine": "American", "name": "Emerald Pub"}

当您使用投影指定要包含在返回文档中的字段时,默认情况下还会包含_id字段。 所有其他字段均会隐式排除。 要从返回文档中删除_id字段,您必须明确将其排除。

在指定要包含的字段时,您还可以从返回的文档中排除 _id字段。 Projections 类提供了 excludeId() 辅助方法,您可以使用该方法省略此字段。

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

collection
.find(equal("name", "Emerald Pub"))
.projection(fields(include("name", "cuisine", "borough"), excludeId()))
.subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"borough": "Manhattan", "cuisine": "American", "name": "Emerald Pub"}
{"borough": "Queens", "cuisine": "American", "name": "Emerald Pub"}

要指定要从结果中排除的字段,请将 projection() 方法链接到 find() 方法。 Projections 类提供了 exclude() 辅助方法,您可以使用该方法设立要排除的字段。

以下示例使用 find() 方法查找 name字段值为 "Emerald Pub" 的所有餐厅。然后,代码调用 projection()exclude() 方法,指示查找操作忽略结果中的 nameaddress 字段:

collection
.find(equal("name", "Emerald Pub"))
.projection(exclude("name", "address"))
.subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))
{"_id": {"$oid": "..."}, "borough": "Manhattan", "cuisine": "American",
"grades": [...], "restaurant_id": "40367329"}
{"_id": {"$oid": "..."}, "borough": "Queens", "cuisine": "American",
"grades": [...], "restaurant_id": "40668598"}

当您使用投影指定要排除的字段时,任何未指定的字段都将隐式包含在返回文档中。

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

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

后退

指定要返回的文档