Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 643
StSch Avatar asked Mar 20 '18 13:03

StSch


People also ask

How do I make one field unique in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.

What is _class field in MongoDB?

By default, Spring Data MongoDB fills the _class field with the fully qualified class name of the entity class. This means that if we do any refactoring involving class names or package names, we will have to do search & replace all over the database.


1 Answers

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;
like image 104
V.Aggarwal Avatar answered Oct 07 '22 01:10

V.Aggarwal