Docs Menu
Docs Home
/ / /
C Driver
/

Work with Indexes

On this page

  • Overview
  • Operational Considerations
  • Sample Data
  • Create an Index
  • Remove an Index
  • API Documentation

In this guide, you can learn how to use indexes with the C driver. Indexes can improve the efficiency of queries and add functionality to querying and storing documents.

Without indexes, MongoDB must scan every document in a collection to find the documents that match each query. These collection scans are slow and can negatively affect the performance of your application. However, if an appropriate index exists for a query, MongoDB can use the index to limit the documents it must inspect.

To improve query performance, build indexes on fields that appear often in your application's queries and operations that return sorted results. Each index that you add consumes disk space and memory when active, so we recommend that you track index memory and disk usage for capacity planning. In addition, when a write operation updates an indexed field, MongoDB updates the related index, which can negatively impact performance for write operations.

You can use wildcard indexes in your MongoDB application to query against fields whose names are not known in advance or are arbitrary. Wildcard indexes are not designed to replace workload-based index planning.

For more information about designing your data model and choosing indexes appropriate for your application, see the Data Modeling and Indexes guide in the MongoDB Server manual.

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.

MongoDB supports several different index types to help query your data. The following pages describe the most common index types and provide sample code for creating each index type.

  • Single-Field Indexes

  • Compound Indexes

  • Multikey Indexes

  • Atlas Search Indexes

You can remove any unused index except the default unique index on the _id field. Pass a mongoc_collection_t structure, the index name, and an optional bson_error_t structure to the mongoc_collection_drop_index() function to remove an index from a collection.

The following example removes an index with the name "_title_" from the movies collection:

bson_error_t error;
if (mongoc_collection_drop_index (collection, "_title_", &error)) {
printf ("Successfully dropped index\n");
} else {
fprintf (stderr, "Failed to drop index: %s", error.message);
}

Note

You cannot remove a single field from a compound text index. You must drop the entire index and create a new one to update the indexed fields.

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

Back

Indexes