在MongoDB中添加唯一索引,忽略空值

时间:2013-06-05 01:20:32

标签: mongodb indexing database

我正在尝试在MongoDB中的一组字段上添加唯一索引。并非所有这些字段都可用于所有文档,我只想索引具有所有字段的字段。

所以,我正试图运行这个:

db.mycollection.ensureIndex({date:1, type:1, reference:1}, {sparse: true, unique: true})

但是我在一个错过'type'字段的字段上收到错误E11000 duplicate key error index(其中有很多字段并且它们是重复的,但我只是想忽略它们。)

是否有可能在MongoDB中或有一些解决方法?

2 个答案:

答案 0 :(得分:3)

有多个人想要这个功能,因为没有解决方法,我建议在jira.mongodb.org投票推荐功能请求Jira门票:

请注意,因为785会提供一种强制执行此功能的方法,所以2193标记为“将无法修复”,因此投票并将您的评论添加到785可能会更高效。

答案 1 :(得分:0)

唯一性,您可以保证,使用upsert操作而不是插入。这将确保如果某个文档已经存在,那么它将在文档不存在时更新或插入

test:Mongo > db.test4.ensureIndex({ a : 1, b : 1, c : 1}, {sparse : 1})

test:Mongo > db.test4.update({a : 1, b : 1}, {$set : { d : 1}}, true, false)
test:Mongo > db.test4.find()
{ "_id" : ObjectId("51ae978960d5a3436edbaf7d"), "a" : 1, "b" : 1, "d" : 1 }
test:Mongo > db.test4.update({a : 1, b : 1, c : 1}, {$set : { d : 1}}, true, false)
test:Mongo > db.test4.find()
{ "_id" : ObjectId("51ae978960d5a3436edbaf7d"), "a" : 1, "b" : 1, "d" : 1 }
{ "_id" : ObjectId("51ae97b960d5a3436edbaf7e"), "a" : 1, "b" : 1, "c" : 1, "d" : 1 }
相关问题