Docs Menu
Docs Home
/ /

返すフィールドを指定する

このガイドでは、プロジェクションを使用して、読み取り操作から返されるフィールドを指定する方法を学習できます。 プロジェクションは、MongoDB がクエリから返すフィールドを指定するドキュメントです。

このガイドの例では、restaurants sample_restaurantsAtlasサンプルデータセットの データベース内の コレクションを使用します。 MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 MongoDBを使い始めるガイドを参照してください

プロジェクションを使用して、返されるドキュメントに含めるフィールドを指定したり、除外するフィールドを指定したりできます。

プロジェクションに含める特定のフィールドを指定すると、他のすべてのフィールドは暗黙的に除外されます(デフォルトで含まれる_idフィールドを除く)。 _idフィールドを除外しない限り、1 つのプロジェクションに包含ステートメントと除外ステートメントを組み合わせることはできません。

返されたドキュメントから_idフィールドを削除するには、明示的に除外する必要があります。

次の例では、 mongoc_collection_find_with_opts() 関数を使用して、nameフィールドの値が "Emerald Pub" であるすべてのレストランを検索します。 これは、mongoc_collection_find_with_opts() のオプション パラメータを使用して返されたドキュメントの namecuisineborough フィールドのみを返すプロジェクションを指定します。

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フィールドを除外しています。

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 Server マニュアルのプロジェクト フィールド ガイドを参照してください。

このガイドで説明した関数や型の詳細については、次のAPIドキュメントを参照してください。

戻る

ドキュメントの検索

項目一覧