1

I have a few objects in a MongoDB database where the _id field was assigned an integer by mistake, how can I in the MongoDB shell replace these integers with an ObjectId?

An example of such an object would look like this:

{ "_id" : 0 }
aknuds1
  • 65,625
  • 67
  • 195
  • 317

1 Answers1

4

The best solution I found was to clone each each object to another with an ObjectId value assigned to _id, and then delete all objects with an integer for _id. I did the following in the shell:

// $type: 16 means int32
> db.Roles.find({_id: {$type: 16}}).forEach(function (x) {
          x._id = ObjectId();
          db.Roles.save(x);
      })
> db.Roles.remove({_id: {$type: 16}})
aknuds1
  • 65,625
  • 67
  • 195
  • 317
  • 2
    Yea that's probably the best way, of course you cannot update the `_id` field so you do have to write it out again. – Sammaye Jan 24 '13 at 15:33