我正在收集用户的数据。这将是非常基本的,包括用户的电子邮件,用户的密码(散列)和字符串数组。
{
email: 'user@example.com',
password: 'password hash',
arr: []
}
我想确保不能有两个具有相同email
的插入内容。
我读到默认情况下mongoDB的_id
是唯一的,它使用一些特殊的数据结构来提高性能。
如何确保email
保持唯一,如果可能,我可以利用_id
字段提供的效果优势吗?
修改:我还要确保null
没有email
个值,并且没有不包含email
字段的文档。
答案 0 :(得分:7)
使用unique关键字,或者只是将_id值设为电子邮件。
db.collection.ensureIndex( { email: 1 }, { unique: true } )
答案 1 :(得分:7)
答案 2 :(得分:5)
Mongodb ensureIndex
已deprecated,请改用createIndex
。
db.collection.createIndex( { email: 1 }, { unique: true } )