Spring Boot 2.3.0 - MongoDB 库不自动创建索引

Spring Boot 2.3.0 - MongoDB Library does not create indexes automatically

我提供了一个示例项目来阐明这个问题:https://github.com/nmarquesantos/spring-mongodb-reactive-indexes

根据 spring mongo 数据库文档 (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.

在我的播放器 class 中,我们可以观察到 @Document 和 @Indexed 注释:

@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;
}
}`

并且在我的应用程序 class 中,我正在插入一个元素来检查数据库是否已成功填充:

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

    playerRepository.save(player).subscribe();

}

如果我在 运行 我的应用程序之后检查 MongoDb,我可以看到集合和元素已成功创建。

昵称的唯一索引未创建。我只能看到为 @Id 属性创建的索引。我错过了什么吗?我是否误解了文档?

Spring 数据 Mongo 数据库版本 Spring Boot 2.3。0.RELEASE 是 3.0.0.RELEASE。由于 Spring 数据 MongoDB 3.0,the auto-index creation is disabled by default.

要启用自动索引创建,设置 spring.data.mongodb.auto-index-creation = true 或者如果您有自定义 Mongo 配置,override the method autoIndexCreation

@Configuration
public class CustomMongoConfig extends AbstractMongoClientConfiguration {

  @Override
  public boolean autoIndexCreation() {
    return true;
  }

  // your other configuration
}

我在将 spring 启动版本升级到 2.3.x 时遇到了这个问题,并在配置 class 上覆盖了这个方法解决了它(@yejianfengblue 上面说的)

  @Override
  public boolean autoIndexCreation() {
    return true;
  }