Ishan
Ishan

Reputation: 3395

How to make user's email unique in mongoDB?

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.

Upvotes: 26

Views: 61085

Answers (3)

smolinari
smolinari

Reputation: 711

You can do it by creating a unique index for your email field.

http://docs.mongodb.org/manual/tutorial/create-a-unique-index/

Upvotes: 15

achuth
achuth

Reputation: 1212

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

db.collection.createIndex( { email: 1 }, { unique: true } )

Upvotes: 29

Mikko
Mikko

Reputation: 1947

Mongodb ensureIndex has been deprecated, use createIndex instead.

db.collection.createIndex( { email: 1 }, { unique: true } )

Upvotes: 16

Related Questions