Mongodb确保一个阵列字段唯一

时间:2018-03-09 02:03:14

标签: arrays mongodb unique

我想让电子邮件变得与众不同。我尝试使用' unique'并且' dropDups',但它不起作用。知道我应该用什么吗?

var custSchema = new Schema({ 
  "username": String,
  "Password": String,
  "email": {["Type": String,
             "Value": { type : String, lowercase: true, unique: true, dropDups: true}]
})  

csv数据示例:

        username       Password            Email
                                      Type     Value
User1:   test1        asdub**jhas    Primary   test1@user1.com
User2:   test2        3kjnn**8man    Primary   Pract@test.com
User3:   test3        dsffs**as97    Primary   test1@user1.com

在此示例中,只有两个用户添加到数据库:User1和User2,因为User3具有与User1相同的电子邮件地址。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

使用选项email.Valueunique: true创建索引,这有助于我们阻止插入电子邮件ID的重复值。

db.collection_name.createIndex({"email.Value":1}, {unique:true})

参考文献:

CreateIndex

Another SO Question

答案 1 :(得分:0)

可能还有其他解决方案可以解决此问题。但在我尝试将“电子邮件”定义为

之后
"Email": [
{"Type": String,
  "Value": { type : String, lowercase: true, index: {unique: true, dropDups: true}}
}]

它工作正常。

相关问题