小编典典

如何更新一个 MongoDB 文档的 _id?

all

我想更新_id一个文档的字段。我知道这不是一个很好的做法。但由于某种技术原因,我需要更新它。

如果我尝试更新它,我会得到:

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

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

并且更新被拒绝。我怎样才能更新它?


阅读 1558

收藏
2022-09-02

共1个答案

小编典典

你不能更新它。您必须使用新的 保存文档_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")})
2022-09-02