Docs Menu
Docs Home
/ /

複合インデックス

複合インデックス は、コレクションのドキュメント内の複数のフィールドへの参照を保持し、クエリとソートのパフォーマンスを向上させます。mongoc_collection_create_indexes_with_opts()複合インデックスを作成するには、{3 関数を使用します。

複合インデックスを作成するときは、次のコンポーネントを指定する必要があります。

  • インデックスを作成するフィールド。

  • 各フィールドの並べ替え順序(昇順または降順)。 昇順の場合は BCON_INT32(1) を指定し、降順の場合は BCON_INT32(-1) を指定します。

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

次の例では、 typeフィールドとgenresフィールドに複合インデックスを作成し、両方のフィールドを昇順でインデックス付けします。

bson_error_t error;
bson_t *keys = BCON_NEW("type", BCON_INT32(1), "genres", BCON_INT32(1));
mongoc_index_model_t *index_model = mongoc_index_model_new(keys, NULL);
if (mongoc_collection_create_indexes_with_opts(collection, &index_model, 1, NULL, NULL, &error)) {
printf("Successfully created index\n");
} else {
fprintf(stderr, "Failed to create index: %s", error.message);
}
bson_destroy(keys);
mongoc_index_model_destroy(index_model);

次の例では、前述のコードサンプルで作成されたインデックスを使用するクエリを実行します。

const bson_t *doc;
bson_t *filter = BCON_NEW("type", BCON_UTF8("movie"),
"genres", BCON_UTF8("Drama"));
mongoc_cursor_t *results =
mongoc_collection_find_with_opts(collection, filter, NULL, NULL);
while (mongoc_cursor_next(results, &doc)) {
char *str = bson_as_canonical_extended_json(doc, NULL);
printf("%s\n", str);
bson_free(str);
}
mongoc_cursor_destroy(results);
bson_destroy(filter);
{ "_id" : ..., "genres" : [ "Crime", "Drama" ], "title" : "Traffic in Souls", "type" : "movie", ... }
{ "_id" : ..., "genres" : [ "Drama" ], "title" : "Laugh, Clown, Laugh", "type" : "movie", ... }
{ "_id" : ..., "genres" : [ "Drama", "Romance" ], "title" : "A Woman of Paris: A Drama of Fate", "type" : "movie", ... }
{ "_id" : ..., "genres" : [ "Drama", "Romance", "Thriller" ], "title" : "He Who Gets Slapped", "type" : "movie", ... }
{ "_id" : ..., "genres" : [ "Drama", "Romance" ], "title" : "Wild Oranges", "type" : "movie", ... }
...

複合インデックスの詳細については、 マニュアルの「 複合インデックスMongoDB Server 」を参照してください。

複合インデックスを使用した効果的なインデックス戦略の詳細については、 MongoDB Serverマニュアルの 「 ESR ルール 」 を参照してください。

このガイドで説明されているメソッドの詳細については、次の API ドキュメントを参照してください。

戻る

単一フィールド インデックス

項目一覧