如何更新一个 MongoDB 文档的 _id? [英] How to update the _id of one MongoDB Document?

查看:75
本文介绍了如何更新一个 MongoDB 文档的 _id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您无法更新它.您必须使用新的 _id 保存文档,然后删除旧文档.

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

这篇关于如何更新一个 MongoDB 文档的 _id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆