I 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 ?
To do it for your whole collection you can also use a loop (based on Niels example):
In this case UserId was the new ID I wanted to use
In case, you want to rename _id in same collection (for instance, if you want to prefix some _ids):
if (doc._id.indexOf("2019:") != 0) {... needed to prevent infinite loop, since forEach picks the inserted docs, even throught .snapshot() method used.
Here I have a solution that avoid multiple requests, for loops and old document removal.
You can easily create a new idea manually using something like:
_id:ObjectId()
But knowing Mongo will automatically assign an _id if missing, you can use aggregate to create a$project
containing all the fields of your document, but omit the field _id. You can then save it with$out
So if your document is:
Then your query will be:
You cannot update it. You'll have to save the document using a new
_id
, and then remove the old document.