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

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

我要更新一个文档的_id MongoDB。我知道这不是很好的做法。但出于一些技术上的原因,我需要更新它。但如果我想更新它,我会:

> db.clients.update({'_id':ObjectId("4cc45467c55f4d2d2a000002")}, {'$set':{'_id':ObjectId("4c8a331bda76c559ef000004")}});Mod on _id not allowed

更新也没有完成。我怎么才能真正更新它?


小唯快跑啊
浏览 3374回答 3
3回答

弑天下

你不能更新它。您必须使用新的_id,然后删除旧文档。// store the document in a variabledoc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})// set a new _id on the documentdoc._id = ObjectId("4c8a331bda76c559ef000004")// insert the document, using the new _iddb.clients.insert(doc)// remove the document with the old _iddb.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})

当年话下

要对整个集合执行此操作,还可以使用一个循环(基于Niels示例):db.status.find().forEach(function(doc){      doc._id=doc.UserId; db.status_new.insert(doc);});db.status_new.renameCollection("status", true);在本例中,userid是我想使用的新ID。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

MongoDB