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

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

问题描述

我想更新一个文档的_id字段.我知道这不是一个很好的实践.但是由于某些技术原因,我需要对其进行更新.如果我尝试更新它,则会得到:

I want update an _id field of one document. I know it's not a really good pratice. But with some technical reason, I need 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 not made. 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天全站免登陆