Manage Collection Indexes

To create indexes on a MongoDB collection, use mongoc_collection_create_indexes_with_opts():

// `keys` represents an ascending index on field `x`.
bson_t *keys = BCON_NEW ("x", BCON_INT32 (1));
mongoc_index_model_t *im = mongoc_index_model_new (keys, NULL /* opts */);
if (mongoc_collection_create_indexes_with_opts (
       coll, &im, 1, NULL /* opts */, NULL /* reply */, &error)) {
   printf ("Successfully created index\n");
} else {
   bson_destroy (keys);
   HANDLE_ERROR ("Failed to create index: %s", error.message);
}
bson_destroy (keys);

To list indexes, use mongoc_collection_find_indexes_with_opts():

mongoc_cursor_t *cursor =
   mongoc_collection_find_indexes_with_opts (coll, NULL /* opts */);
printf ("Listing indexes:\n");
const bson_t *got;
while (mongoc_cursor_next (cursor, &got)) {
   char *got_str = bson_as_canonical_extended_json (got, NULL);
   printf ("  %s\n", got_str);
   bson_free (got_str);
}
if (mongoc_cursor_error (cursor, &error)) {
   mongoc_cursor_destroy (cursor);
   HANDLE_ERROR ("Failed to list indexes: %s", error.message);
}
mongoc_cursor_destroy (cursor);

To drop an index, use mongoc_collection_drop_index_with_opts(). The index name may be obtained from the keys document with mongoc_collection_keys_to_index_string():

bson_t *keys = BCON_NEW ("x", BCON_INT32 (1));
char *index_name = mongoc_collection_keys_to_index_string (keys);
if (mongoc_collection_drop_index_with_opts (
       coll, index_name, NULL /* opts */, &error)) {
   printf ("Successfully dropped index\n");
} else {
   bson_free (index_name);
   bson_destroy (keys);
   HANDLE_ERROR ("Failed to drop index: %s", error.message);
}
bson_free (index_name);
bson_destroy (keys);

For a full example, see example-manage-collection-indexes.c.