Reputation: 67997
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 }
Upvotes: 1
Views: 1447
Reputation: 67997
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}})
Upvotes: 4