Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb change ObjectID or _id attribute for a document?

How can I change an objects id? It doesn't seem to be just a regular attribute, so I'm not sure if I'm able to update that value?

I'm using Ruby with Mongoid, but I can't figure out how using just the ruby driver, any help would be appreciated!

like image 387
JP Silvashy Avatar asked Sep 15 '11 00:09

JP Silvashy


2 Answers

MongoDB won't let you update the _id field of a document, but you can delete the document and reinsert it with a new _id value.

like image 70
Chris Fulstow Avatar answered Nov 15 '22 09:11

Chris Fulstow


So when you create the items; you can specify your own ID; however you can't change it once it's been created as it's a unique identifier for the row.

A bit more on the Object Id

If you want to specify them when creating your items you can do: {_id: 'YourUniqueID'} which will override it. More information in that above link.

Hope this helps!

like image 27
Petrogad Avatar answered Nov 15 '22 09:11

Petrogad