如何更新一个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")})

当年话下
TA贡献1890条经验 获得超9个赞
db.status.find().forEach(function(doc){ doc._id=doc.UserId; db.status_new.insert(doc);});db.status_new.renameCollection("status", true);
- 3 回答
- 0 关注
- 3323 浏览
添加回答
举报
0/150
提交
取消