Docs Menu
Docs Home
/ / /
Kotlin Sync Driver
/

Work with Indexes

On this page

  • Overview
  • Operational Considerations
  • Sample Data
  • Create an Index
  • Remove an Index
  • Delete a Single Index
  • Delete All Indexes
  • API Documentation

In this guide, you can learn how to use indexes with the Kotlin Sync 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

  • Atlas Search and Vector Search Indexes

You can remove any unused index except the default unique index on the _id field.

The following sections show how to remove a single index or how to remove all indexes in a collection.

Pass an index name to the dropIndex() method to remove an index from a collection.

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

collection.dropIndex("_title_")

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.

You can drop all indexes by calling the dropIndexes() method on your collection:

collection.dropIndexes()

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

Back

Indexes