Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Spring Data MongoDB lets you describe indexes in mapping metadata or create and manage them explicitly through index operations. The key production detail: index annotations do not, by themselves, guarantee that MongoDB creates indexes automatically. Automatic creation is disabled by default in the documented behavior, so choose and configure an index lifecycle deliberately.

Choose between metadata and explicit index management

Approach How it works Best suited to
Mapping metadata Declare index intent on mapped properties or document types. Automatic creation is a separate setting and is disabled by default in the documented behavior. Keeping index definitions close to entity mappings, when automatic creation is intentionally enabled or metadata will be resolved by application code.
Explicit index operations Resolve mapping metadata if desired, then create or maintain indexes through Spring’s index operations. Applications that need deliberate lifecycle control, including setup after startup or handling collections recreated while the application is running.

Spring Data’s reference recommends explicit creation when application-controlled index management is needed: it cannot automatically create indexes for collections recreated while the application is running. See the Spring Data MongoDB index-management reference for the documented lifecycle guidance.

Declare index intent in mapping metadata

Single-field indexes with @Indexed

Place @Indexed on a mapped property to describe a single-field index. For example:

@Document
class Person {
    @Indexed
    private String name;
}

Compound indexes with @CompoundIndex

Use the type-level @CompoundIndex annotation to describe an index spanning multiple fields. A compound index is one ordered index definition over those fields, so choose its field order to match the application’s query and sort patterns rather than treating it as several independent single-field indexes.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Automatic index creation applies to types annotated with @Document, and it is disabled by default in the documented behavior. Spring Data says it must be explicitly enabled; this has been the documented requirement since version 3.0. Verify the setting and behavior for the Spring Data MongoDB version in use rather than assuming an annotation creates an index in production. See the mapping and index-management reference and Spring Data MongoDB mapping reference.

Create indexes explicitly during application startup

For controlled setup, resolve index definitions from mapping metadata and apply them through the relevant collection’s IndexOperations. Spring’s reference describes doing this after the application context has refreshed, for example in response to ContextRefreshedEvent.

@EventListener(ContextRefreshedEvent.class)
public void createIndexes() {
    MappingContext<?, ?> mappingContext = mongoTemplate.getConverter().getMappingContext();
    IndexResolver resolver = new MongoPersistentEntityIndexResolver(mappingContext);

    mappingContext.getPersistentEntities().forEach(entity -> {
        if (entity.isAnnotationPresent(Document.class)) {
            IndexOperations operations = mongoTemplate.indexOps(entity.getType());
            resolver.resolveIndexFor(entity.getType()).forEach(operations::createIndex);
        }
    });
}

This pattern uses MongoPersistentEntityIndexResolver to derive definitions from annotations and applies each definition through the entity’s index operations. Adapt imports and lifecycle wiring to the application and Spring Data version. The code illustrates the explicit approach; it does not make index changes safe to perform blindly against every live collection.

A simple direct creation example is:

mongoTemplate.indexOps(Person.class)
    .createIndex(new Index().on("name", Sort.Direction.ASC));

The index-management reference includes examples using ensureIndex, but the current API marks ensureIndex deprecated since Spring Data MongoDB 4.5 in favor of createIndex. Check the API for the version your project uses; older releases may differ in available methods and signatures. See the collection and index management reference and the IndexOperations API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Inspect and maintain indexes

Call indexOps with an entity class when Spring should derive the collection name, or with a collection name when working directly against that collection. IndexOperations supports creating, altering, dropping one index, dropping all indexes, and listing index details with getIndexInfo(). The reactive template exposes reactive counterparts.

IndexOperations operations = mongoTemplate.indexOps(Person.class);
List<IndexInfo> indexes = operations.getIndexInfo();

Index changes affect a live collection. Coordinate them with deployment and data constraints: for example, a unique index cannot be established if existing documents violate its uniqueness requirement. Inspect the collection and planned change before applying it.

Select index options for the data and query

Option Effect Choose it when
Unique Enforces uniqueness for indexed values. The data model requires the indexed key or key combination to be unique, and existing data satisfies that rule.
Sparse Omits documents that lack the indexed field. Excluding documents without that field matches the intended lookup and uniqueness semantics.
Partial filter Includes only documents matching the specified filter. Queries and data rules benefit from indexing a defined subset of documents.
TTL Configures expiration behavior for indexed documents, according to MongoDB TTL rules. Time-based deletion is a deliberate retention policy, not merely a query optimization.
Collation Defines language-sensitive string comparison behavior for the index. Queries use a compatible collation; a collation-specific index is useful only when query collation aligns with it.
Hidden Makes the index unavailable to the query planner. You intentionally need to keep an index from being considered by the planner while retaining it in the collection.

Spring’s Index API exposes these choices, but none is a universal default. Match the option to the application’s uniqueness rules, document inclusion, expiry policy, string comparison, or planner needs. See the Spring Data Index API.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Imperative and reactive applications

With imperative code, use MongoTemplate and its indexOps methods. Reactive applications can use ReactiveMongoTemplate and reactive index-operation counterparts for creating, altering, dropping, and listing indexes. Choose the API that matches the application’s data-access model; the index lifecycle considerations remain the same.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not use background as a current performance switch

The Spring Data background index attribute is deprecated for removal in Spring Data MongoDB 5.0, and MongoDB 4.2 ignores the server flag. Do not recommend or rely on it as a current way to make index creation less disruptive. Confirm index-build behavior against the MongoDB server version and deployment requirements. See the Index API documentation.

Version note

The cited lifecycle reference is Spring Data MongoDB 5.0.7 and notes 5.1.1 as the latest stable version at the time of that documentation snapshot; related API references include 5.1.0 and 5.1.1. Because index APIs and deprecations vary by release, verify examples against the exact Spring Data MongoDB version used by the application.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.