如何使用户的电子邮件在 mongoDB 中唯一?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28514120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make user's email unique in mongoDB?
提问by Ishan
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.
我想确保不能有两个具有相同email
. 我读到_id
mongoDB 的默认情况下是唯一的,它使用一些特殊的数据结构来提高性能。
How can I make sure that the email
remains unique, and if possible can I leverage the performance benefits provided by the _id
field ?
我如何确保email
保持唯一性,如果可能,我可以利用该_id
领域提供的性能优势吗?
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.
编辑:我还想确保没有null
值,email
并且没有不包含该email
字段的文档。
采纳答案by Skooppa.com
You can do it by creating a unique index for your email field.
您可以通过为电子邮件字段创建唯一索引来实现。
http://docs.mongodb.org/manual/tutorial/create-a-unique-index/
http://docs.mongodb.org/manual/tutorial/create-a-unique-index/
Scott
斯科特
回答by achuth
回答by Mikko
Mongodb ensureIndex
has been deprecated, use createIndex
instead.
MongodbensureIndex
已被弃用,请createIndex
改用。
db.collection.createIndex( { email: 1 }, { unique: true } )
db.collection.createIndex( { email: 1 }, { unique: true } )