我想更新一个文档的 _id
字段。我知道这不是一个很好的做法。但由于某些技术原因,我需要更新它。
如果我尝试更新它,我会得到:
db.clients.update({ _id: ObjectId("123")}, { $set: { _id: ObjectId("456")}})
Performing an update on the path '_id' would modify the immutable field '_id'
并且更新被拒绝。如何更新?
最佳答案
您无法更新它。您必须使用新的 _id
保存文档,然后删除旧文档。
// 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")})
https://stackoverflow.com/questions/4012855/