Search code examples
pythonmongodbpymongo

"Update" _id in mongodb document


PS: I only have to do this due to business requirements

I'm able to achieve it using mongosh, but since there are multiple records to be updated, I'm trying to implement a simple python script to automate the task.

Is it possible to do this with pymongodb?

// store the document in a variable
doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})

// set a new _id on the document
doc._id = ObjectId("4c8a331bda76c559ef000004")

// insert the document, using the new _id
db.clients.insert(doc)

// remove the document with the old _id
db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})

I'm not able to set the new Id in the doc variable in order to insert the new document that will mirror the old one.

Thanks


Solution

  • Here's a pymongo equivalent:

    from pymongo import MongoClient
    from bson import ObjectId
    
    db = MongoClient()['mydatabase']
    
    old_doc_id = '4cc45467c55f4d2d2a000002'
    new_doc_id = '4c8a331bda76c559ef000004'
    
    doc = db.clients.find_one({'_id': ObjectId(old_doc_id)})
    
    if doc is not None:
        #  set a new _id on the document
        doc['_id'] = ObjectId(new_doc_id)
    
        # insert the document, using the new _id
        db.clients.insert_one(doc)
    
        # remove the document with the old _id
        db.clients.delete_one({'_id': ObjectId(old_doc_id)})