The _id
field of a document is immutable, as discussed in this documentation. Attempting to modify its value would result in an error/exception, as in:
> db.foo.drop()
> db.foo.insert({ _id: 1 })
> db.foo.update({ _id: 1 }, { $set: { _id: 3 }})
Mod on _id not allowed
> db.foo.find()
{ "_id" : 1 }
If you do need to alter the identifier of a document, you could fetch it, modify the _id
value, and then re-persist the document using insert()
or save()
. insert()
may be safer on the off chance that you new _id
value conflicts and you're rather see a uniqueness error than overwrite the existing document (as save()
would do). Afterwards, you'll need to go back and remove the original document.
Since you can't do all of this in a single atomic transaction, I would suggest the following order of operations:
findOne()
existing document by its _id
- Modify the returned document's
_id
property
insert()
the modified document back into the collection
- If the
insert()
succeeded, remove()
the old document by the original _id