Docs Menu
Docs Home
/ / /
C Driver
/ /

Multikey Indexes

On this page

  • Overview
  • Sample Data
  • Create a Multikey Index
  • API Documentation

Multikey indexes are indexes that improve performance for queries on array-valued fields. You can define a multikey index by using the same syntax as a single field or compound index.

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.

The following example creates a multikey index on the cast field:

bson_error_t error;
bson_t *keys = BCON_NEW ("cast", 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 ("cast", BCON_UTF8 ("Viola Davis"));
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" : ..., "cast" : [ "Kelsey Grammer", "Cary Elwes", "Viola Davis", "John C. McGinley" ], "title" : "The Pentagon Wars", ... }
{ "_id" : ..., "cast" : [ "George Clooney", "Natascha McElhone", "Viola Davis", "Jeremy Davies" ], "title" : "Solaris", ... }
{ "_id" : ..., "cast" : [ "Meryl Streep", "Philip Seymour Hoffman", "Amy Adams", "Viola Davis" ], "title" : "Doubt", ... }
{ "_id" : ..., "cast" : [ "Hugh Jackman", "Jake Gyllenhaal", "Viola Davis", "Maria Bello" ], "title" : "Prisoners", ... }
{ "_id" : ..., "cast" : [ "Emma Stone", "Viola Davis", "Bryce Dallas Howard", "Octavia Spencer" ], "title" : "The Help", ... }
...

Multikey indexes behave differently from other indexes in terms of query coverage, index bound computation, and sort behavior. To learn more about multikey indexes, including a discussion of their behavior and limitations, see the Multikey Indexes guide in the MongoDB Server manual.

To learn more about any of the functions discussed in this guide, see the following API documentation:

Back

Compound Indexes