MongoDB 显示重复键为空?

tao*_*iko 5 mongodb

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)

Ste*_*nie 6

如果您定义了非稀疏的唯一索引,则这是预期的情况:缺少具有唯一索引的字段的值的文档将具有索引值null。这意味着集合中只有一个文档可以缺少唯一字段。

重复键消息包括索引名称和键违规:

"errmsg" : "E11000 重复键错误集合:testdb.setup index: name dup key: { : null }",

在您的示例中,setup数据库中的集合在testdbname字段上具有唯一索引。尝试的 upsert 失败,因为name缺少该字段,并且此集合中已经有一个缺少 或null值为的文档name

如果您想使用唯一索引而不要求该字段存在,您有几个选择: