To answer the topics question - you can’t really change the _id of a document. You can create a copy of the document and assign a new _id to the new document (and optionally delete the old document)
The doc.UserId in the example is just a value of the document. You can assign any unique value to the _id you want. The example does not really change the _id – it creates a new document in a new collection and then renames the collection. I’m not sure this works and looks really dirty and I suggest you to use the accepted answer of that stackoverflow question:
// 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")})
I am generating a new collections on the fly so it needs to be in a loop. Also, why would the accepted answer be correct when the id are hardcoded and not for a loop? Could you modify the accepted answer but for a loop and not using hardcoded IDs? Thanks