mongoDB中的索引数组/子对象会导致重复键错误 [英] Indexing array/subobject in mongoDB causes duplicate key error
问题描述
我有一个集合,我将有一个 _children
属性,如下所示:
I have a collection where I will have a _children
attribute like this:
{
_children: {
videoTags: [ { id: '1', name: 'one'}, { id: '2', name: 'two'} ],
},
a: 10
}
因为我会搜索videoTags ,我创建了一个索引:
Since I WILL search in videoTags, I create an index as such:
> db.test4.createIndex({ "_children.videosTags.id" : 1 }, { "unique" : true } );
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
麻烦的是,我不能再将任何添加到该表中重复的索引错误。以下是如何重现它:
Trouble is, I can no longer add anything to that table since I get a duplicate index error. Here is how to reproduce it:
- 第1步:插入集合
db.test4.insert({a:20})
WriteResult({nInserted:1})
- 第2步:制作索引
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 ::由:: 11000引起E11000重复键错误索引:wonder_1.test4。$ _ children。 videosTags.id_1 dup key:{:null}
}
})
我认为这里的问题是已经一条记录,其中没有定义_children.videoTags.id。
I think the issue here is that there is already a record where _children.videoTags.id is not defined.
然而,我所期望的是一种行为如果 if videoTags.id被指定,那么它必须是唯一的。相反,一个空的被认为是被采取的键。
However, what I expected was a behaviour where if videoTags.id was specified, it needed to be unique. Instead, an empty one is considered a "taken" key.
我在做什么是愚蠢的错?
如果您没有将 unique
设置为 true
,这将有效,但我觉得我需要修正它...
What am I doing that is stupidly wrong?
This will work if you don't set unique
as true
, but I have the feeling I need to fix it for real...
推荐答案
可能有两个原因。
-
集合中可能存在其他文件,其中包含相同的
_children.videosTags.id
很可能多个文档可能缺少 _children.videosTags.id
或具有空值。
It's quite possible that more than one document may have missing _children.videosTags.id"
or having null value.
当您创建唯一
键时,null或空值会给你带来困难解决方法是创建稀疏
索引,如果你的MongoDB版本是3.2+,则创建部分索引。参见文档。
As you are creating unique
key, null or empty values are give you tough time. Solution is either create sparse
index and if your MongoDB version is 3.2+, create partial index. See documentation for partial indexes.
这篇关于mongoDB中的索引数组/子对象会导致重复键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!