7

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("my@email.com"))
userRepository.save(new User("my@email.com"))

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.

cnmuc
  • 6,025
  • 2
  • 24
  • 29

3 Answers3

15

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
times29
  • 2,782
  • 2
  • 21
  • 40
0

Check - https://docs.mongodb.com/manual/core/index-unique/

It states - MongoDB cannot create a unique index on the specified index field(s) if the collection already contains data that would violate the unique constraint for the index.

So if your collection if u have few documents already having the same email value then if u are trying to create index on email field, it might not work. Check if you have such documents.

Rahul Vedpathak
  • 1,346
  • 3
  • 16
  • 30
0

I solved the issue following this question: Spring Data: Unique field in MongoDB document

So you should make the index in the MongoTemplate + the @indexed annotation.