指定要返回的字段
概述
在本指南中,您可以通过使用 投影 来了解如何指定从读取操作返回的字段。投影是一个文档,它指定MongoDB从查询返回哪些字段。
示例数据
本指南中的示例使用来自restaurants
集合的 sample_restaurants
数据库中的示例数据。有关创建免费MongoDB Atlas集群并加载数据集的说明,请参阅Atlas 示例数据集指南。开始使用 Atlas。
投影类型
您可以使用投影来指定要在返回文档中包含哪些字段,或指定要排除哪些字段。
在指定要包含在投影中的某些字段时,所有其他字段都将隐式排除(除默认包含的 _id
字段外)。您不能在单个投影中组合包含和排除语句,除非您正在排除 _id
字段。
要从返回的文档中删除 _id
字段,必须 显式排除它。
指定要包含的字段
以下示例使用 mongoc_collection_find_with_opts()
函数查找所有名称字段值为 "Emerald Pub"
的餐厅。它通过使用 mongoc_collection_find_with_opts()
的选项参数指定了一个投影,只返回返回文档的 name
、cuisine
和 borough
字段。
const bson_t *doc; bson_t *filter = BCON_NEW ("name", BCON_UTF8 ("Emerald Pub")); bson_t *opts = BCON_NEW ("projection", "{", "name", BCON_BOOL (true), "cuisine", BCON_BOOL (true), "borough", BCON_BOOL (true), "}"); mongoc_cursor_t *results = mongoc_collection_find_with_opts (collection, filter, opts, NULL); while (mongoc_cursor_next (results, &doc)) { char *str = bson_as_canonical_extended_json (doc, NULL); printf ("%s\n", str); bson_free (str); } bson_destroy (filter); bson_destroy (opts); mongoc_cursor_destroy (results);
{ "_id" : { "$oid" : "..." }, "borough" : "Manhattan", "cuisine" : "American", "name" : "Emerald Pub" } { "_id" : { "$oid" : "..." }, "borough" : "Queens", "cuisine" : "American", "name" : "Emerald Pub" }
排除 _id
字段
在指定要包含的字段时,您还可以从返回的文档中排除 _id
字段。
以下示例运行与前面示例相同的查询,但将投影中的 _id
字段排除
const bson_t *doc; bson_t *filter = BCON_NEW ("name", BCON_UTF8 ("Emerald Pub")); bson_t *opts = BCON_NEW ("projection", "{", "name", BCON_BOOL (true), "cuisine", BCON_BOOL (true), "borough", BCON_BOOL (true), "_id", BCON_BOOL (false), "}"); mongoc_cursor_t *results = mongoc_collection_find_with_opts (collection, filter, opts, NULL); while (mongoc_cursor_next (results, &doc)) { char *str = bson_as_canonical_extended_json (doc, NULL); printf ("%s\n", str); bson_free (str); } bson_destroy (filter); bson_destroy (opts); mongoc_cursor_destroy (results);
{ "borough" : "Manhattan", "cuisine" : "American", "name" : "Emerald Pub" } { "borough" : "Queens", "cuisine" : "American", "name" : "Emerald Pub" }
更多信息
要了解更多关于投影的信息,请参阅 MongoDB 服务器手册中的投影字段指南。
API 文档
要了解更多关于本指南中讨论的任何函数或类型,请参阅以下 API 文档