MongoDB 3.6 版
执行此操作时,我收到了重复的密钥消息。实际问题是什么?
mongos> db.setup.findAndModify({
... query : {"_id" : ObjectId("5b3c7abbea95705803084cad")},
... update : {$set : { "test" : "xxxx" }},
... upsert : true
... })
2018-07-06T10:13:22.749+0000 E QUERY [thread1] Error: findAndModifyFailed failed: {
"ok" : 0,
"errmsg" : "E11000 duplicate key error collection: testdb.setup index: name dup key: { : null }",
"code" : 11000,
"codeName" : "DuplicateKey",
"$clusterTime" : {
"clusterTime" : Timestamp(1530872002, 603),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
},
"operationTime" : Timestamp(1530872002, 602)
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DBCollection.prototype.findAndModify@src/mongo/shell/collection.js:724:1
@(shell):1:1
mongos>
Run Code Online (Sandbox Code Playgroud)
如果您定义了非稀疏的唯一索引,则这是预期的情况:缺少具有唯一索引的字段的值的文档将具有索引值null。这意味着集合中只有一个文档可以缺少唯一字段。
重复键消息包括索引名称和键违规:
"errmsg" : "E11000 重复键错误集合:testdb.setup index: name dup key: { : null }",
在您的示例中,setup数据库中的集合在testdb该name字段上具有唯一索引。尝试的 upsert 失败,因为name缺少该字段,并且此集合中已经有一个缺少 或null值为的文档name。
如果您想使用唯一索引而不要求该字段存在,您有几个选择:
删除并重新创建具有以下sparse属性的唯一索引:
db.setup.createIndex(
{name: 1},
{unique:true, sparse:true}
)
Run Code Online (Sandbox Code Playgroud)使用部分过滤器表达式删除并重新创建唯一索引(如果需要,它允许进一步的条件):
db.setup.createIndex(
{ name: 1},
{ unique:true, partialFilterExpression: {name: {$exists:true }}}
)
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
15145 次 |
| 最近记录: |