【问题标题】:pymongo renaming the indexed key throws duplicate key errorpymongo 重命名索引键会引发重复键错误
【发布时间】:2019-07-09 21:44:07
【问题描述】:

以下是mongodb中的文档。在尝试重命名索引键时,它会引发重复键错误。我想重命名索引键而没有任何错误。请帮助我实现这一目标

以下是“ne-mgmt”数据库和“NEs”集合中存在的文档。

Mongo 文档:

{
        "_id" : ObjectId("5d15c50dbea32e000199569b"),
        "created_ts" : NumberLong("1561707789892"),
        "is_error" : "NO",
        "user_id" : "",
        "gne_port" : "34149",
        "passwd" : "",
        "target_id" : "cmbrmawa-0111105b",
        "region" : "Massachusetts",
        "ne_status" : "ASSIGNED",
}

以下是重命名索引键时面临的错误 错误:

rs0:PRIMARY> db.NEs.update({}, {$rename:{"target_id":"TARGET_ID"}}, false, true);
WriteResult({
        "nMatched" : 0,
        "nUpserted" : 0,
        "nModified" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "E11000 duplicate key error collection: ne-mgmt-db.NEs index: target_id dup key: { : null }"
        }
})

使用 getIndexes() 方法检查索引。当我尝试删除索引并尝试重命名它时工作正常。但我想要它而不删除索引。

索引:

rs0:PRIMARY> db.NEs.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "ne-mgmt-db.NEs"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "target_id" : 1
                },
                "name" : "target_id",
                "ns" : "ne-mgmt-db.NEs"
        }
]

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    您可能只在target_id 字段上创建unique 索引。

    db.getCollection('localdatabases').createIndex({ target_id: 1 }, { unique: true })
    

    现在,当使用$rename 运算符运行更新命令时,同一字段的其他字段,即新的TARGET_ID 设置为null,因此它会为与null 具有相同值的多个字段引发错误。

    因此,为了避免 at 情况,您还需要设置 sparse 索引。

    db.getCollection('localdatabases').createIndex({ target_id: 1 }, { unique: true, sparse: true })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 2018-07-21
      • 2019-01-05
      • 2021-10-25
      相关资源
      最近更新 更多