我提供了一个示例项目来阐明此问题:https://github.com/nmarquesantos/spring-mongodb-reactive-indexes
根据spring mongo db文档(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.
在我的Player类中,我们可以同时观察@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;
}
}`
并且在我的应用程序类中,我正在插入一个元素以检查是否已成功填充数据库:
@PostConstruct
public void seedData() {
var player = new Player("Cristiano Ronaldo", "CR7");
playerRepository.save(player).subscribe();
}
如果在运行应用程序后检查MongoDb,则可以看到集合和成功创建的元素。
未创建昵称的唯一索引。我只能看到为@Id属性创建的索引。我有什么想念的吗?我是否误解了文档?
Spring Boot 2.3.0附带的Spring Data MongoDB版本。RELEASE是3.0.0.RELEASE。从Spring Data MongoDB 3.0开始,the auto-index creation is disabled by default.
要启用自动索引创建,请设置spring.data.mongodb.auto-index-creation = true
,或者如果您具有自定义的Mongo配置,请设置override the method autoIndexCreation
autoIndexCreation