为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

小唯快跑啊 2019-07-22 20:19:51
如何更新一个MongoDB文档的_id?我要更新一个文档的_id MongoDB。我知道这不是很好的做法。但出于一些技术上的原因,我需要更新它。但如果我想更新它,我会:> db.clients.update({'_id':ObjectId("4cc45467c55f4d2d2a000002")}, {'$set':{'_id':ObjectId("4c8a331bda76c559ef000004")}});Mod on _id not allowed更新也没有完成。我怎么才能真正更新它?
查看完整描述

3 回答

?
弑天下

TA贡献1818条经验 获得超8个赞


你不能更新它。您必须使用新的_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")})


查看完整回答
反对 回复 2019-07-22
?
当年话下

TA贡献1890条经验 获得超9个赞

要对整个集合执行此操作,还可以使用一个循环(基于Niels示例):

db.status.find().forEach(function(doc){ 
    doc._id=doc.UserId; db.status_new.insert(doc);});db.status_new.renameCollection("status", true);

在本例中,userid是我想使用的新ID。


查看完整回答
反对 回复 2019-07-22
  • 3 回答
  • 0 关注
  • 3323 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信