如何更新一個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 關注
- 3364 瀏覽
添加回答
舉報
0/150
提交
取消