指定要返回的字段
概述
在本指南中,您可以了解如何使用 C++ 驱动程序通过使用 投影 来指定从读取操作中返回哪些字段。投影是一个文档,它指定 MongoDB 从查询中返回哪些字段。
示例数据
本指南中的示例使用的是restaurants
集合,该集合位于 sample_restaurants
数据库中,来自Atlas 示例数据集。要从您的 C++ 应用程序访问此集合,请实例化一个连接到 Atlas 集群的 mongocxx::client
,并将以下值分配给您的 db
和 collection
变量
auto db = client["sample_restaurants"]; auto collection = db["restaurants"];
要了解如何创建免费的 MongoDB Atlas 集群并加载示例数据集,请参阅 Atlas 入门指南。
投影类型
您可以使用投影来指定要包含在返回文档中的字段,或者指定要排除的字段。除非您正在排除 _id
字段,否则您不能在单个投影中组合包含和排除语句。
指定要包含的字段
要指定结果中要包含的字段,请创建一个 mongocxx::options::find
类的实例并设置其 projection
字段。要设置此字段,请使用以下语法
<options instance>.projection(make_document(kvp("<field name>", 1)));
以下示例将 mongocxx::options::find
对象的 projection
字段设置为仅返回匹配文档的 name
、cuisine
和 borough
字段。然后调用 find()
方法以查找所有 name
字段值为 "Emerald Pub"
的餐厅,并将 mongocxx::options::find
对象作为参数传递给 find()
mongocxx::options::find opts{}; opts.projection(make_document(kvp("name", 1), kvp("cuisine", 1), kvp("borough", 1))); auto cursor = collection.find(make_document(kvp("name", "Emerald Pub")), opts); for(auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; }
{ "_id" : { "$oid" : "..." }, "borough" : "Manhattan", "cuisine" : "American", "name" : "Emerald Pub" } { "_id" : { "$oid" : "..." }, "borough" : "Queens", "cuisine" : "American", "name" : "Emerald Pub" }
当使用投影来指定返回文档中要包含的字段时,默认情况下也会包含 _id
字段。所有其他字段都隐式排除。要从返回文档中删除 _id
字段,必须 显式排除它。
排除 _id
字段
指定要包含的字段时,还可以从返回的文档中排除 _id
字段。
以下示例执行与上一个示例相同的查询,但将投影中的 _id
字段排除
mongocxx::options::find opts{}; opts.projection(make_document(kvp("_id", 0), kvp("name", 1), kvp("cuisine", 1), kvp("borough", 1))); auto cursor = collection.find(make_document(kvp("name", "Emerald Pub")), opts); for(auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; }
{ "borough" : "Manhattan", "cuisine" : "American", "name" : "Emerald Pub" } { "borough" : "Queens", "cuisine" : "American", "name" : "Emerald Pub" }
指定要排除的字段
要指定结果中要排除的字段,创建一个 mongocxx::options::find
类的实例并设置其 projection
字段。要设置此字段,请使用以下语法
<options instance>.projection(make_document(kvp("<field name>", 0)));
以下示例将 projection
字段设置为一个 mongocxx::options::find
对象,以排除匹配文档的 grades
和 address
字段。然后调用 find()
方法来查找所有 name
字段值为 "Emerald Pub"
的餐厅,并将 mongocxx::options::find
对象作为参数传递给 find()
mongocxx::options::find opts{}; opts.projection(make_document(kvp("grades", 0), kvp("address", 0))); auto cursor = collection.find(make_document(kvp("name", "Emerald Pub")), opts); for(auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; }
{ "_id" : { "$oid" : "..." }, "borough" : "Manhattan", "cuisine" : "American", "name" : "Emerald Pub", "restaurant_id" : "40367329" } { "_id" : { "$oid" : "..." }, "borough" : "Queens", "cuisine" : "American", "name" : "Emerald Pub", "restaurant_id" : "40668598" }
当您使用投影来指定要排除的字段时,任何未指定的字段将隐式包含在返回的文档中。
更多信息
要了解有关投影的更多信息,请参阅 MongoDB 服务器手册中的 投影字段 指南。
API 文档
要了解更多关于本指南中讨论的任何方法或类型的信息,请参阅以下 API 文档