Create Indexes in Spring Data MongoDB

Using @Indexed
This annotation marks the field as indexed in MongoDB:

public class User {
    private String name;

but as of Spring Data MongoDB 3.0, automatic index creation is turned off by default.

We can, however, change that behavior by explicitly overriding autoIndexCreation() method in our MongoConfig:

public class MongoConfig extends AbstractMongoClientConfiguration {

    // rest of the config goes here

    protected boolean autoIndexCreation() {
        return true;

We can create other types of index using these attributes :


Create an Index Programmatically

  ensureIndex(new Index().on("name", Direction.ASC));

Compound Indexes

MongoDB supports compound indexes, where a single index structure holds references to multiple fields.

    @CompoundIndex(name = "email_age", def = "{'' : 1, 'age': 1}")
public class User {