Compound Indexes
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.
When creating a compound index, you must specify the following components:
The fields to index.
The sort order for each field (ascending or descending). Specify
BCON_INT32 (1)
for ascending order andBCON_INT32 (-1)
for descending order.
Sample Data
The examples in this guide use the movies
collection in the sample_mflix
database from the Atlas sample datasets. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the
Get Started with Atlas guide.
Create a Compound Index
The following example creates a compound index on the type
and genres
fields, with
both fields indexed in ascending order:
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);
The following example performs a query that uses the index created in the preceding code sample:
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", ... } ...
Additional Information
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 Documentation
To learn more about any of the methods discussed in this guide, see the following API documentation: