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?
@Indexed(name = "nick_name_index")
. Also did you try to save duplicates to test index? – Guesthouse