Overview
Compound indexes hold references to multiple fields within a collection's documents, improving query and sort performance. Use the mongoc_collection_create_indexes_with_opts() function to create compound indexes.
複合インデックスを作成するときは、次のコンポーネントを指定する必要があります。
インデックスを作成するフィールド。
各フィールドの並べ替え順序(昇順または降順)。 昇順の場合は
BCON_INT32(1)を指定し、降順の場合はBCON_INT32(-1)を指定します。
サンプル データ
このガイドの例では、Atlas サンプルデータセットの sample_mflix データベースの movies コレクションを使用します。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);
詳細情報
To learn more about compound indexes, see Compound Indexes in the MongoDB Server manual.
To learn about effective indexing strategies using compound indexes, see The ESR Rule in the MongoDB Server manual.
API ドキュメント
このガイドで説明されているメソッドの詳細については、次の API ドキュメントを参照してください。