Reddy Bhavani Prasad
Reddy Bhavani Prasad

Reputation: 1115

pymongo renaming the indexed key throws duplicate key error

Following are the documents in the mongodb. While trying to rename the indexed key, it throws the duplicate key error. I want to rename the indexed keys without any error. Please help me to achieve this

Following are the documents present in the "ne-mgmt" database and "NEs" collection.

Mongo Documents:

{
        "_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",
}

Following is the error faced while renaming the indexed key Error:

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 }"
        }
})

Checking for indexes using the getIndexes() method. When I try to drop the index and try to rename it is working fine. But I want it without dropping the index.

Indexes:

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"
        }
]

Upvotes: 1

Views: 241

Answers (1)

Ashh
Ashh

Reputation: 46491

You are probably creating only unique index on the target_id field.

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

Now when running update command with $rename operator other fields for the same field i.e. for new TARGET_ID are set as null and thererfore it throws error for the multiple fields having the same value as null.

So to avoid the at situation you need to set sparse index as well.

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

Upvotes: 1

Related Questions