Akku
Akku

Reputation: 4454

Manually change MongoID

Through the PHP problem when inserting stuff into MongoDB explained in the answer by Denver Matt in this question I created duplicate IDs in a dataset in MongoDB. Fixing the PHP code is easy, but to be able to still use my dataset I wonder:

Can I change the MongoId manually without breaking something? Or can I just reset this ID somehow into a new one?

Upvotes: 0

Views: 645

Answers (1)

jmikola
jmikola

Reputation: 6922

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

Upvotes: 1

Related Questions