WriteConcern detected an error 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: develop.Test.$AppId_1_UserId_1_Type_1__sub_1__key_1 dup key: { ... }'. (Response was { "ok" : 1, "code" : 11000, "err" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: develop.Test.$AppId_1_UserId_1_Type_1__sub_1__key_1 dup key: {...}).
当我尝试将新条目插入我的集合时,出现上述错误。让我困惑的是我的 key 是 Guid id 字段。该实体具有 AppId 和 UserId 字段,但这些字段不应该是键,也不应该是唯一的。
就在我保存之前,ID 全部为零。将其设置为唯一的 Guid 后,但保存调用会引发 MongoDuplicateKey 错误。 也许是因为我是 Mongo 新手,但我不明白这一点,任何帮助将不胜感激。
更新
获取索引的输出
{
"0" : {
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "develop.Test"
},
"1" : {
"v" : 1,
"unique" : true,
"key" : {
"AppId" : 1,
"UserId" : 1,
"Type" : 1,
"_sub" : 1,
"_key" : 1
},
"name" : "AppId_1_UserId_1_Type_1__sub_1__key_1",
"ns" : "develop.Test"
},
"2" : {
"v" : 1,
"key" : {
"Type" : 1,
"_sub" : 1,
"_g" : 1
},
"name" : "Type_1__sub_1__g_1",
"ns" : "develop.Test"
}
}
最佳答案
您有一个unique compound indexes在 AppId
、UserId
、Type
、sub
和 key
字段上,这就是原因您收到此错误。
"1" : {
"v" : 1,
"unique" : true,
"key" : {
"AppId" : 1,
"UserId" : 1,
"Type" : 1,
"_sub" : 1,
"_key" : 1
},
"name" : "AppId_1_UserId_1_Type_1__sub_1__key_1",
"ns" : "develop.Test"
},
现在如何解决这个问题?
- 如果不是您创建的,那么可能是您的同事或其他人创建的。在这种情况下,您不会在不与他们交谈的情况下删除索引。
您可能想使用
db.collection.dropIndex(index)
删除索引方法db.collection.dropIndex({ AppId: 1, UserId: 1, Type: 1, _sub: 1, _key: 1 })
关于MongoDB 重复键异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31684072/