DEV Community

Sven Glöckner
Sven Glöckner

Posted on

Update _id of MongoDB items

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

While updating the _id is not possible, because this is an immutable field, there is another way to make this happen.

  • iterate through the collection
  • save the old _id in a variable
  • set the new _id field value to ObjectId
  • remove the old item

Sample code:
db.products.find().forEach(function(doc){
var oldId = doc._id
doc._id=ObjectId()
db.products.insert(doc)
db.products.deleteOne({ _id: oldId})
})

Top comments (0)