In a Spring boot + MongoDB application, I'm trying to create an unique index for an email field.
@Document
public class User {
@Id
private String id;
@Indexed(unique = true)
private String email;
}
public interface UserRepository extends MongoRepository<User, String>
But I'm still able to insert two user objects with the same email, so
userRepository.save(new User("[email protected]"))
userRepository.save(new User("[email protected]"))
creates two entries in the user collection.
What am I doing wrong?
I'm aware of Spring Data MongoDB - Where to create an index programmatically for a Mongo collection?, but I'm looking for a "annotation-only" solution.
I cite the documentation:
Spring Data MongoDB can automatically create indexes for entity types annotated with @Document. Index creation must be explicitly enabled since version 3.0 to prevent undesired effects with collection lifecycle and performance impact.
Did you enable automatic index creation? Because if you didn't, that will most likely be the reason why your unique constraint is not honored. You can verify that no index is existing by connecting to your MongoDB instance and running db.user.getIndexes()
. This will print the indexes for your user collection.
With Spring Boot you can enable automatic index creation with the following config in your application.yml
:
spring:
data:
mongodb:
auto-index-creation: true
Or if you prefer properties:
spring.data.mongodb.auto-index-creation=true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With