问题与
unique compound
索引有关,这与其他仅具有unique
索引的此类问题不同。我也有sparse: true
索引。
我的收藏中有以下索引
[
{
"v": 2,
"key": {
"_id": 1
},
"name": "_id_",
"ns": "somedb.votes"
},
{
"v": 2,
"key": {
"answerId": 1
},
"name": "answerId_1",
"ns": "somedb.votes",
"sparse": true,
"background": true
},
{
"v": 2,
"key": {
"questionId": 1
},
"name": "questionId_1",
"ns": "somedb.votes",
"sparse": true,
"background": true
},
{
"v": 2,
"unique": true,
"key": {
"answerId": 1,
"votedBy": 1
},
"name": "answerId_1_votedBy_1",
"ns": "somedb.votes",
"sparse": true,
"background": true
},
{
"v": 2,
"unique": true,
"key": {
"questionId": 1,
"votedBy": 1
},
"name": "questionId_1_votedBy_1",
"ns": "somedb.votes",
"sparse": true,
"background": true
}
]
我在集合中有以下文档
{
"_id": ObjectId("59fdd3ce915511329553dfaa"),
"updatedAt": ISODate("2017-11-04T14:54:22.110Z"),
"votedAt": ISODate("2017-11-04T14:50:54.681Z"),
"questionId": ObjectId("59fc77e45a857465a90339cc"),
"value": -1,
"votedBy": ObjectId("59fc4274aa686d39abe5d58a"),
"type": "QuestionVote",
"__v": 0
}
现在当我尝试执行以下
db.votes.insert({ questionId: ObjectId("59fc798d5a857465a90339cf"), value: -1, votedBy: ObjectId("59fc4274aa686d39abe5d58a"), type: 'QuestionVote', _id: ObjectId("5a003240bfd8194a02d0add8") })
我收到以下错误
E11000 duplicate key error collection: somedb.votes index: answerId_1_votedBy_1 dup key: { : null, : ObjectId('59fc4274aa686d39abe5d58a') }
WriteResult({
"nInserted": 0,
"writeError": {
"code": 11000,
"errmsg": "E11000 duplicate key error collection: somedb.votes index: answerId_1_votedBy_1 dup key: { : null, : ObjectId('59fc4274aa686d39abe5d58a') }"
}
})
我不明白原因。索引是sparse
和compound
。但错误只是因为存在相同的votedBy
字段。
即执行以下,
db.votes.insert({votedBy: ObjectId("59fc4274aa686d39abe5d58a")})
即使votedBy
对象上没有明确的索引,我也会收到以下错误。
E11000 duplicate key error collection: somedb.votes index: answerId_1_votedBy_1 dup key: { : null, : ObjectId('59fc4274aa686d39abe5d58a') }
WriteResult({
"nInserted": 0,
"writeError": {
"code": 11000,
"errmsg": "E11000 duplicate key error collection: somedb.votes index: answerId_1_votedBy_1 dup key: { : null, : ObjectId('59fc4274aa686d39abe5d58a') }"
}
})
参考:复合索引 - https://docs.mongodb.com/manual/core/index-compound/#compound-indexes