Search code examples
mongodb

How to update the _id of one MongoDB Document?


I want update an _id field of one document. I know it's not really good practice. But for some technical reason, I need to update it.

If I try to update it I get:

db.clients.update({ _id: ObjectId("123")}, { $set: { _id: ObjectId("456")}})

Performing an update on the path '_id' would modify the immutable field '_id'

And the update is rejected. How I can update it?


Solution

  • You cannot update it. You'll have to save the document using a new _id, and then remove the old document.

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