如何使用户的电子邮件在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:18:17  来源:igfitidea点击:

How to make user's email unique in mongoDB?

mongodbindexing

提问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 _idof mongoDB is unique by default, and it uses some special data structure for improved performance.

我想确保不能有两个具有相同email. 我读到_idmongoDB 的默认情况下是唯一的,它使用一些特殊的数据结构来提高性能。

How can I make sure that the emailremains unique, and if possible can I leverage the performance benefits provided by the _idfield ?

我如何确保email保持唯一性,如果可能,我可以利用该_id领域提供的性能优势吗?

Edit: I also want to make sure that there are no nullvalues for emailand that there are no documents which do not contain the emailfield.

编辑:我还想确保没有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

Use uniquekeyword, or simply make _id value to be email.

使用唯一关键字,或者简单地将 _id 值设为电子邮件。

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

回答by Mikko

Mongodb ensureIndexhas been deprecated, use createIndexinstead.

MongodbensureIndex已被弃用,请createIndex改用。

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

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