Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make user's email unique in mongoDB?

Tags:

I am making a collection of user's data. This will be pretty basic consisting of user's email, user's password (hashed), and an array of strings.

{     email: '[email protected]',     password: 'password hash',     arr: [] } 

I want to make sure that there can't be two inserts with the same email. I read that the _id of mongoDB is unique by default, and it uses some special data structure for improved performance.

How can I make sure that the email remains unique, and if possible can I leverage the performance benefits provided by the _id field ?

Edit: I also want to make sure that there are no null values for email and that there are no documents which do not contain the email field.

like image 463
Ishan Avatar asked Feb 14 '15 09:02

Ishan


People also ask

How do I make something unique in MongoDB?

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

How do you make a field unique in MongoDB Java?

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 .

Does MongoDB support unique indexes?

Restrictions. 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. You may not specify a unique constraint on a hashed index.

What is the unique index?

Unique indexes are indexes that help maintain data integrity by ensuring that no rows of data in a table have identical key values. When you create a unique index for an existing table with data, values in the columns or expressions that comprise the index key are checked for uniqueness.


1 Answers

Use unique keyword, or simply make _id value to be email.

db.collection.createIndex( { email: 1 }, { unique: true } ) 
like image 120
achuth Avatar answered Oct 06 '22 23:10

achuth