9
votes

let's say I have the following database entity:

@Document(collection = "users")
public class User {

    @Id
    private String id;

    private String firstname;

    private String lastname;

    private String email; 

}

How can I enforce the field email to be unique? That means MongoDB should check if a user record with this email address already exists when the application tries to save the entity.

Regards, Steffen

4
@Indexed(unique = true) - pDer666
So it only works in combination with @Indexed? - StSch

4 Answers

10
votes

Mongodb needs to create and index a field in order to know whether the field is unique or not.

@Indexed(unique=true)
private String email;
4
votes

First, use Indexed annotation above of your field in your model as shown below:

@Indexed(unique = true)
private String email;

Also, you should programmatically define your index. You should use the below code when defining your MongoTemplate.

mongoTemplate.indexOps("YOUR_COLLECTION_NAME").ensureIndex(new Index("YOUR_FEILD_OF_COLLECTION", Direction.ASC).unique());

For your case, you should use:

mongoTemplate.indexOps("users").ensureIndex(new Index("email", Direction.ASC).unique());
1
votes

As of Spring Data MongoDB 3.0, automatic index creation is turned off by default. So basically beside using @Indexed, you have to configure default indexing options. What you need to do is to make spring.data.mongodb.auto-index-creation=true in application.properties file and then @Indexed will work like a charm!

0
votes

*This is work for me but you must delete your database and then re-run your application *

 spring.data.mongodb.auto-index-creation=true