want update an _id MongoDB of one document. I know it’s not a really good pratice. But with some technical reason, I need update it. But If I try to update it I have :
> db.clients.update({‘_id’:ObjectId(“4cc45467c55f4d2d2a000002”)}, {‘$set’:{‘_id’:ObjectId(“4c8a331bda76c559ef000004”)}});
Mod on _id not allowed
And the update is not made. How I can really update it in MongoDB?
You cannot update it. You’ll have to save the document using a new _id, and then remove the old document.
Skip code block
// 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”)})
To do it for your whole collection you can also use a loop (based on Niels example):
db.status.find().forEach(function(doc){ var id=doc._id; doc._id=doc.UserId; db.status.insert(doc); db.status.remove({_id:id}); })