问题
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: 'user@example.com',
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.
回答1:
You can do it by creating a unique index for your email field.
http://docs.mongodb.org/manual/tutorial/create-a-unique-index/
Scott
回答2:
Use unique keyword, or simply make _id value to be email.
db.collection.createIndex( { email: 1 }, { unique: true } )
回答3:
Mongodb ensureIndex has been deprecated, use createIndex instead.
db.collection.createIndex( { email: 1 }, { unique: true } )
来源:https://stackoverflow.com/questions/28514120/how-to-make-users-email-unique-in-mongodb