Single-Field Indexes
For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt
Single-Field Indexes
Overview
Single-field indexes are indexes with a reference to a single field within a collection's documents. They improve single field query and sort performance, and support TTL Indexes that automatically remove documents from a collection after a certain amount of time or at a specific clock time.
When creating a single-field index, you must specify the following:
-
The field on which to create the index.
-
The sort order for the indexed values (ascending or descending). Specify
BCON_INT32(1)for ascending order andBCON_INT32(-1)for descending order.
Note:
The _id_ index is an example of a single-field index. This index is automatically created on the _id field when a new collection is created.
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 MongoDB Get Started guide.
Create Single-Field Index
The following example creates an index in ascending order on the title field:
bson_error_t error;
bson_t *keys = BCON_NEW("title", 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 is an example of a query that is covered by the index created in the preceding code example:
const bson_t *doc;
bson_t *filter = BCON_NEW("title", "Batman");
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);
Output:
{ "_id" : ..., "title" : "Batman", ... }
Additional Information
To learn more about single-field indexes, see Single Field Indexes in the MongoDB Server manual.
API Documentation
To learn more about any of the functions discussed in this guide, see the following API documentation:
