spring-bootspring-data-mongodbspring-mongodb

Spring Boot 2.3.0 - MongoDB Library does not create indexes automatically


I've provided a sample project to elucidate this problem: https://github.com/nmarquesantos/spring-mongodb-reactive-indexes

According to the spring mongo db documentation (https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping-usage):

the @Indexed annotation tells the mapping framework to call createIndex(…) on that property of your document, making searches faster. Automatic index creation is only done for types annotated with @Document.

In my Player class, we can observe the both the @Document and @Indexed annotation:

@Document
public class Player {

@Id
private String id;

private String playerName;

@Indexed(name = "player_nickname_index", unique = true)
private String nickname;


public Player(String playerName, String nickname) {
    this.id = UUID.randomUUID().toString();
    this.playerName = playerName;
    this.nickname = nickname;
}

public String getPlayerName() {
    return playerName;
}

public void setPlayerName(String playerName) {
    this.playerName = playerName;
}

public String getNickname() {
    return nickname;
}

public void setNickname(String nickname) {
    this.nickname = nickname;
}
}`

And in my application class, i'm inserting oneelement to check the database is populated successfully:

@PostConstruct
public void seedData() {
    var player = new Player("Cristiano Ronaldo", "CR7");

    playerRepository.save(player).subscribe();

}

If I check MongoDb after running my application, I can see the collection and the element created successfully.

The unique index for nickname is not created. I can only see an index created for the @Id attribute. Am I missing anything? Did I mis-interpret the documentation?


Solution

  • The Spring Data MongoDB version come with Spring Boot 2.3.0.RELEASE is 3.0.0.RELEASE. Since Spring Data MongoDB 3.0, the auto-index creation is disabled by default.

    To enable auto-index creation, set spring.data.mongodb.auto-index-creation = true or if you have custom Mongo configuration, override the method autoIndexCreation

    @Configuration
    public class CustomMongoConfig extends AbstractMongoClientConfiguration {
    
      @Override
      public boolean autoIndexCreation() {
        return true;
      }
    
      // your other configuration
    }