1MONGOC_MANAGE_COLLECTION_INDEXES(3)libmongocMONGOC_MANAGE_COLLECTION_INDEXES(3)
2
3
4
6 mongoc_manage_collection_indexes - Manage Collection Indexes
7
8 To create indexes on a MongoDB collection, use
9 mongoc_collection_create_indexes_with_opts():
10
11 // `keys` represents an ascending index on field `x`.
12 bson_t *keys = BCON_NEW ("x", BCON_INT32 (1));
13 mongoc_index_model_t *im = mongoc_index_model_new (keys, NULL /* opts */);
14 if (mongoc_collection_create_indexes_with_opts (
15 coll, &im, 1, NULL /* opts */, NULL /* reply */, &error)) {
16 printf ("Successfully created index\n");
17 } else {
18 bson_destroy (keys);
19 HANDLE_ERROR ("Failed to create index: %s", error.message);
20 }
21 bson_destroy (keys);
22
23
24 To list indexes, use mongoc_collection_find_indexes_with_opts():
25
26 mongoc_cursor_t *cursor =
27 mongoc_collection_find_indexes_with_opts (coll, NULL /* opts */);
28 printf ("Listing indexes:\n");
29 const bson_t *got;
30 while (mongoc_cursor_next (cursor, &got)) {
31 char *got_str = bson_as_canonical_extended_json (got, NULL);
32 printf (" %s\n", got_str);
33 bson_free (got_str);
34 }
35 if (mongoc_cursor_error (cursor, &error)) {
36 mongoc_cursor_destroy (cursor);
37 HANDLE_ERROR ("Failed to list indexes: %s", error.message);
38 }
39 mongoc_cursor_destroy (cursor);
40
41
42 To drop an index, use mongoc_collection_drop_index_with_opts(). The in‐
43 dex name may be obtained from the keys document with
44 mongoc_collection_keys_to_index_string():
45
46 bson_t *keys = BCON_NEW ("x", BCON_INT32 (1));
47 char *index_name = mongoc_collection_keys_to_index_string (keys);
48 if (mongoc_collection_drop_index_with_opts (
49 coll, index_name, NULL /* opts */, &error)) {
50 printf ("Successfully dropped index\n");
51 } else {
52 bson_free (index_name);
53 bson_destroy (keys);
54 HANDLE_ERROR ("Failed to drop index: %s", error.message);
55 }
56 bson_free (index_name);
57 bson_destroy (keys);
58
59
60 For a full example, see example-manage-collection-indexes.c.
61
63 MongoDB, Inc
64
66 2017-present, MongoDB, Inc
67
68
69
70
711.24.3 Aug 17, 202M3ONGOC_MANAGE_COLLECTION_INDEXES(3)