Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversRust Driver

Indexes

On this page

  • Overview
  • Query Coverage and Performance
  • Operational Considerations
  • Index Types
  • Single Field Indexes
  • Compound Indexes
  • Multikey Indexes (Array Field Indexes)
  • Clustered Indexes
  • Text Indexes
  • Geospatial Indexes
  • Unique Indexes
  • Remove an Index
  • Additional Information
  • API Documentation

In this guide, you can learn how to use the Rust driver to create and manage indexes. Indexes are special data structures that improve query performance in MongoDB.

If you perform a query on a collection without any indexes, MongoDB scans every document to find matches. These collection scans are slow and can negatively affect the performance of your application. When you create an index that covers your query, MongoDB limits the number of documents it inspects to find matches, which results in improved performance.

Tip

You can use indexes in update operations, delete operations, and some aggregation pipeline stages. To learn more about using indexes in aggregations, see Improve Performance with Indexes and Document Filters in the Server manual.

The following table describes the elements that you can include in a MongoDB query:

Element
Description
Query
Required
Specifies the fields and values to match
Options
Optional
Specify how the query executes
Projection
Optional
Specifies the fields that MongoDB returns in matched documents
Sort
Optional
Specifies the order of documents returned

When your query elements reference fields that are all included in the same index, MongoDB can return results directly from the index. These queries are called covered queries.

To learn how to ensure that your index covers your query, see Covered Query in the Server manual.

Important

Sort Criteria

Your sort criteria must match or invert the order of the index.

Suppose a collection has the following index on the name field in ascending order (A-Z) and the age field in descending order (9-0):

name_1_age_-1

MongoDB uses this index when you sort documents in either of the following configurations:

  • name ascending, age descending

  • name descending, age ascending

If you specify the same sort order for both fields, MongoDB does not use the index and instead performs an in-memory sort.

To improve your query performance, create indexes on fields that appear often in your queries. However, it is a good practice to track index memory and disk usage for capacity planning, because each index consumes disk space and memory. Additionally, if a write operation updates an indexed field, MongoDB also must update the relevant index.

MongoDB supports dynamic schemas, so your application can query against fields with unknown or variable names. If you are connected to MongoDB Server version 4.2 or later, you can create wildcard indexes to support these queries. To learn more about this index type, see Wildcard Indexes in the Server manual.

MongoDB supports multiple index types to support your queries. The following sections describe common index types and show how to create each index type in a collection.

Note

Sample Collections

The examples in this guide use collections from the Atlas sample data. To learn how to import this data, see the Load Sample Data tutorial in the Atlas documentation.

You can use the create_index() and create_indexes() methods to create indexes in a collection. The create_index() method takes an IndexModel struct parameter that you can construct by using the type's builder() method.

To view a full list of index types, see Index Types in the Server manual.

A single field index holds a reference to a document field.

This index improves the performance of single field queries and sorts. It also supports TTL indexes that automatically remove documents from a collection after a certain amount of time. To learn more about TTL indexes, see TTL indexes in the Server manual.

When you create a new collection, MongoDB automatically creates a unique, single field index on the _id field.

The following code creates an ascending index on the city field in the sample_training.zips collection:

let index = IndexModel::builder().keys(doc! { "city": 1 }).build();
let idx = my_coll.create_index(index, None).await?;
println!("Created index:\n{}", idx.index_name);

A compound index holds a reference to multiple document fields.

This index improves the performance of queries and sorts on multiple fields. When you create a compound index, you must specify a direction for each of the indexed fields.

You can create a multikey index by using the same syntax for creating a single field index.

The following code creates a compound index on the city and pop fields in the sample_training.zips collection:

let index = IndexModel::builder()
.keys(doc! { "city": 1, "pop": -1 })
.build();
let idx = my_coll.create_index(index, None).await?;
println!("Created index:\n{}", idx.index_name);

A multikey index holds a reference to an array-valued field. This index improves the performance of queries on array fields.

You can create a multikey index by using the same syntax for creating a single field index.

The following code creates a multikey index on the tags field in the sample_training.posts collection:

let index = IndexModel::builder().keys(doc! { "tags": 1 }).build();
let idx = my_coll.create_index(index, None).await?;
println!("Created index:\n{}", idx.index_name);

Clustered indexes improve the performance of insert, update, and delete operations on clustered collections. Clustered collections store documents ordered by the clustered index key value. To learn more about these collections, see Clustered Collections in the Server manual.

You can create a clustered index only when creating a collection. To create a clustered collection, perform the following steps:

  1. Create a ClusteredIndex instance.

  2. Set the ClusteredIndex instance as the value of the clustered_index field of a CreateCollectionOptions instance.

  3. Pass the options to the create_collection() method.

You must set the following fields of the ClusteredIndex struct:

  • The key field, which specifies the key pattern. The value of this field must be { _id: 1 }.

  • The unique field, which specifies the uniqueness of the index. The value of this field must be true.

To create a ClusteredIndex instance that automatically uses the required values, you can call the type's default() method.

The following code creates a clustered index with default configuration on the _id field when creating a new collection called items in the sample_training database:

let db = client.database("sample_training");
let cl_idx = ClusteredIndex::default();
let opts = CreateCollectionOptions::builder()
.clustered_index(cl_idx)
.build();
db.create_collection("items", opts).await?;

A text index supports text search queries on string content. This index references a field with a string value or a string array value. MongoDB supports text search for several languages. When you create a text index, you can specify the default language as an option.

A collection can only contain one text index. To create a text index on multiple text fields, you can create a compound index. When you run a text search after creating a compound index, the search operation runs on all the text fields in the compound index.

Tip

Atlas Full Text Search

Text indexes are different from Atlas full text search indexes. To learn more about Atlas Search indexes, see the Atlas Search Indexes guide.

The following code creates a text index on the body field in the sample_training.posts collection. The code sets an option to specify "spanish" as the default language for the text index:

let idx_opts = IndexOptions::builder()
.default_language("spanish".to_string())
.build();
let index = IndexModel::builder()
.keys(doc! { "body": "text" })
.options(idx_opts)
.build();
let idx = my_coll.create_index(index, None).await?;
println!("Created index:\n{}", idx.index_name);

MongoDB supports queries containing geospatial coordinate data by using 2dsphere indexes. You can create a 2dsphere index on a field with GeoJSON object values.

This index type supports the following tasks:

  • Queries on geospatial data to find inclusion, intersection, and proximity

  • Calculation of distances on a Euclidean plane

Important

You cannot create two geospatial indexes on the same field.

The following sample document in the sample_mflix.theaters collection contains the field location.geo. This field has a GeoJSON point value:

{
"_id": ...,
"theaterId": ...,
"location": {
"address": ...,
"geo": {
"type": "Point",
"coordinates": [
-93.24565,
44.85466
]
}
}
}

The following code creates a geospatial 2dsphere index on the location.geo field in the sample_mflix.theaters collection:

let index = IndexModel::builder()
.keys(doc! { "location.geo": "2dsphere" })
.build();
let idx = my_coll.create_index(index, None).await?;
println!("Created index:\n{}", idx.index_name);

A unique index ensures that the indexed fields do not store duplicate values. By default, MongoDB creates a unique, single field index on the _id field when you create a collection.

To create a unique index, specify the field or combination of fields that you want to maintain uniqueness for and set the unique option to true.

The following code shows how to set the unique field to true in an IndexOptions instance and pass these options when creating an IndexModel:

let opts = IndexOptions::builder().unique(true).build();
let index = IndexModel::builder()
.keys(doc! { "_id": -1 })
.options(opts)
.build();

You can remove, or drop, any indexes from a collection except the default unique index on the _id field. To remove an index, pass the name of the index to the drop_index() method.

Tip

Remove All Indexes

You can remove all the indexes on a collection except for the _id index at once by using the drop_indexes() method.

The following example removes an index called city_1 from the sample_training.zips collection:

my_coll.drop_index("city_1".to_string(), None).await?;

To learn more about designing data models and creating appropriate indexes for your application, see Indexing Strategies and Operational Factors and Data Models in the Server manual.

To learn about performing read operations, see the guides in the Read Operations category.

To learn more about the concepts mentioned in this guide, see the following Server documentation:

To learn more about the methods and types mentioned in this guide, see the following API documentation:

←  AggregationAtlas Search Indexes →