19

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.

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
StSch
  • 377
  • 1
  • 4
  • 12

6 Answers6

22

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;
V.Aggarwal
  • 557
  • 4
  • 12
10

This worked for me, but you have to delete your database and then re-run your application

 spring.data.mongodb.auto-index-creation=true
Yassine Moumen
  • 109
  • 1
  • 4
8

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());
Ahmad Vatani
  • 1,630
  • 4
  • 21
  • 34
6

As of Spring Data MongoDB 3.0, automatic index creation is turned off by default. So basically, besides 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 the application.properties file, and then @Indexed will work like a charm!

1

You can try one of the below solutions, it worked for me.

Note: Please delete your db before you re-try with the below solutions.

Solution - 1

@Indexed(unique = true, background = true)
private String emailId;

Solution - 2

Add spring.data.mongodb.auto-index-creation=true to your application.properties file.

or

Add spring.data.mongodb.auto-index-creation:true to your yaml file

0

If anyone has a custom Mongo configuration -> spring.data.mongodb.auto-index-creation:true won't work. Instead try adding this to your MongoConfig:

       @Override
       public boolean autoIndexCreation() {
       return true;
       }

It solved the problem for me....