'Spring Data: Unique field in MongoDB document
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
Solution 1:[1]
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;
Solution 2:[2]
This worked for me, but you have to delete your database and then re-run your application
spring.data.mongodb.auto-index-creation=true
Solution 3:[3]
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());
Solution 4:[4]
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!
Solution 5:[5]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | V.Aggarwal |
| Solution 2 | Mohamad Chamanmotlagh |
| Solution 3 | Ahmad Vatani |
| Solution 4 | |
| Solution 5 | Robin Xavier |
