Spring Data MongoDB
MongoMappingContext
autoIndexCreation
MongoConfigurationSupport
database indexing

Please use 'MongoMappingContextsetAutoIndexCreationboolean' or override 'MongoConfigurationSupportautoIndexCreation' to be explicit

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

That Spring Data MongoDB warning is asking you to make an indexing decision explicit instead of relying on framework defaults. The fix is straightforward: either enable automatic index creation for annotated entities or override the configuration to keep it disabled on purpose.

Why Spring Data Wants An Explicit Choice

Spring Data can derive MongoDB indexes from annotations such as @Indexed, @CompoundIndex, and @TextIndexed. In older setups, developers sometimes assumed those indexes would always be created automatically. Newer versions push you to declare the behavior yourself because index creation affects startup time, migrations, and production safety.

If automatic index creation is enabled, the application checks mapped entities and creates missing indexes at startup. That is convenient in development and tests, but it can be risky in production on large collections because index builds may be expensive.

The warning appears so your team has a deliberate policy instead of an accidental one.

Option 1: Override autoIndexCreation()

If your application extends AbstractMongoClientConfiguration, the clearest fix is to override autoIndexCreation():

java
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import org.springframework.context.annotation.Configuration;
4import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
5
6@Configuration
7public class MongoConfig extends AbstractMongoClientConfiguration {
8
9    @Override
10    protected String getDatabaseName() {
11        return "appdb";
12    }
13
14    @Override
15    public MongoClient mongoClient() {
16        return MongoClients.create("mongodb://localhost:27017");
17    }
18
19    @Override
20    protected boolean autoIndexCreation() {
21        return true;
22    }
23}

This configuration tells Spring Data to build indexes declared in your domain model. It is the most direct answer when you want annotations to drive schema support.

Here is a matching entity:

java
1import org.springframework.data.annotation.Id;
2import org.springframework.data.mongodb.core.index.Indexed;
3import org.springframework.data.mongodb.core.mapping.Document;
4
5@Document("users")
6public class User {
7
8    @Id
9    private String id;
10
11    @Indexed(unique = true)
12    private String email;
13
14    private String displayName;
15}

On startup, Spring Data will ensure an index exists for email.

Option 2: Configure MongoMappingContext

If your configuration style exposes a MongoMappingContext bean directly, you can set the flag there:

java
1import org.springframework.context.annotation.Bean;
2import org.springframework.context.annotation.Configuration;
3import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
4import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
5
6@Configuration
7public class MongoMappingConfig {
8
9    @Bean
10    MongoMappingContext mongoMappingContext(MongoCustomConversions conversions) throws ClassNotFoundException {
11        MongoMappingContext context = new MongoMappingContext();
12        context.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
13        context.setAutoIndexCreation(true);
14        return context;
15    }
16}

Use this style only if it fits the rest of your configuration. In most Spring Boot applications, overriding autoIndexCreation() is simpler and easier for other developers to find.

Choosing The Right Policy

A practical rule is:

  • Enable automatic index creation in local development and integration tests.
  • Be cautious in production, especially when collections are large or index changes are controlled by migrations.

Many teams disable auto creation in production and apply indexes through a deployment step or migration tool. That gives better operational control and avoids surprise work during application startup.

If you choose manual management, you can still create indexes with MongoTemplate:

java
1import org.springframework.boot.ApplicationRunner;
2import org.springframework.context.annotation.Bean;
3import org.springframework.context.annotation.Configuration;
4import org.springframework.data.domain.Sort;
5import org.springframework.data.mongodb.core.MongoTemplate;
6import org.springframework.data.mongodb.core.index.Index;
7
8@Configuration
9public class IndexBootstrap {
10
11    @Bean
12    ApplicationRunner ensureIndexes(MongoTemplate mongoTemplate) {
13        return args -> mongoTemplate.indexOps("users")
14            .ensureIndex(new Index().on("email", Sort.Direction.ASC).unique());
15    }
16}

That approach is explicit and works well when index rollout must be reviewed.

Common Pitfalls

One common mistake is enabling auto index creation and assuming existing bad data will be ignored. For a unique index, duplicate values will cause creation to fail. Clean the data first or the application may fail during startup.

Another pitfall is scattering configuration. If one class sets MongoMappingContext#setAutoIndexCreation(true) while another configuration overrides the default in a different way, the resulting behavior can be hard to reason about. Pick one configuration pattern and document it.

Developers also sometimes assume the warning means something is broken. It does not. It only means Spring Data wants you to declare whether index generation should happen automatically.

Finally, do not treat annotated indexes as a substitute for query analysis. An annotation makes intent visible, but you still need to design indexes around actual query patterns, write volume, and collection size.

Summary

  • The warning asks you to choose index creation behavior explicitly.
  • Override autoIndexCreation() when using AbstractMongoClientConfiguration.
  • Set MongoMappingContext#setAutoIndexCreation(true) only if that matches your configuration style.
  • Automatic creation is convenient in development but can be risky in production.
  • Unique and compound indexes still require careful data cleanup and operational planning.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.