Search code examples
mongodbmongodb-shell

How can I change the type of objects' _id field to ObjectId in the MongoDB shell?


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 }

Solution

  • 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}})