【发布时间】:2016-06-28 23:27:31
【问题描述】:
我有一个集合,其中有一个 _children 属性,如下所示:
{
_children: {
videoTags: [ { id: '1', name: 'one'}, { id: '2', name: 'two'} ],
},
a: 10
}
由于我将在 videoTags 中搜索,因此我创建了一个索引:
> db.test4.createIndex({ "_children.videosTags.id" : 1 }, { "unique" : true } );
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
问题是,我无法再将 anything 添加到该表中,因为我收到重复索引错误。以下是如何重现它:
- 第 1 步:插入到集合中
db.test4.insert({a:20})
WriteResult({ "nInserted" : 1 })
- 第二步:制作索引
db.test4.createIndex({ "_children.videosTags.id" : 1 }, { "unique" : true } );
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
- 第 3 步:再次尝试插入
db.test4.insert({a:30})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: wonder_1.test4.$_children.videosTags.id_1 dup key: { : null }"
}
})
我认为这里的问题是已经一条记录没有定义_children.videoTags.id。
但是,我所期望的是 if videoTags.id 指定的行为,它需要是唯一的。取而代之的是,一个空的密钥被视为“已获取”密钥。
我在做什么这是愚蠢的错误?
如果您不将unique 设置为true,这将起作用,但我觉得我需要真正修复它...
【问题讨论】:
-
这将是因为另一个文档已经有一个空数组(或至少一个没有
"id"字段的元素。您可以使用"sparse",或确保所有数组元素都有一个@987654331 @ 字段。将您知道将在数组元素上放置的"unique"索引(即使您真的想要一个唯一的 id 集合)可能会充满问题。通常不建议这样做。 -
感谢您的回答——就是这样!