指定要返回的字段
Overview
在本指南中,您可以学习;了解如何使用Scala驾驶员通过投影来指定从读取操作中返回哪些字段。投影是指定MongoDB从查询中返回哪些字段的文档。
样本数据
本指南中的示例使用restaurants
sample_restaurants
Atlas示例数据集的 数据库中的 集合。要从Scala应用程序访问权限此集合,请创建一个连接到AtlasMongoClient
集群的 ,并将以下值分配给database
和collection
变量:
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()
方法,指示查找操作仅返回匹配文档的 name
、cuisine
和 borough
字段:
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
字段
在指定要包含的字段时,您还可以从返回的文档中排除 _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()
方法,指示查找操作忽略结果中的 name
和 address
字段:
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 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: