我想更新一个文档的_id
字段.我知道这不是很好的练习.但是由于一些技术原因,我需要更新它.
如果我try 更新它,我会得到:
db.clients.update({ _id: ObjectId("123")}, { $set: { _id: ObjectId("456")}})
Performing an update on the path '_id' would modify the immutable field '_id'
更新被拒绝.我如何更新它?
我想更新一个文档的_id
字段.我知道这不是很好的练习.但是由于一些技术原因,我需要更新它.
如果我try 更新它,我会得到:
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")})