如何在mongoDB中使用户的电子邮件独一无二?

时间:2015-02-14 09:12:32

标签: mongodb indexing

我正在收集用户的数据。这将是非常基本的,包括用户的电子邮件,用户的密码(散列)和字符串数组。

{
    email: 'user@example.com',
    password: 'password hash',
    arr: []
}

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

如何确保email保持唯一,如果可能,我可以利用_id字段提供的效果优势吗?

修改:我还要确保null没有email个值,并且没有不包含email字段的文档。

3 个答案:

答案 0 :(得分:7)

使用unique关键字,或者只是将_id值设为电子邮件。

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

答案 1 :(得分:7)

您可以通过为电子邮件字段创建唯一索引来完成此操作。

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

斯科特

答案 2 :(得分:5)

Mongodb ensureIndexdeprecated,请改用createIndex

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