0

I have a collection (510 documents) where _id are numbers :

{    "_id" : "1",
    "name" : "eric" }

{    "_id" : "2",
    "name" : "tom" }
....

and I want to change their values to ObjectId() to be like this:

{    "_id" : ObjectId("53849e258bf3be07804a00d0"),
    "name" : "eric" }

{    "_id" : ObjectId("53849e388bf3be07804a00d1"),
    "name" : "tom" }
....

so I tried:

db.contacts.find().forEach(function(doc) {
    db.contacts.update(
        { "_id": doc._id },
        { "$set": { "_id": ObjectId()} }
    );
    })

but it doesn't work, I got like result:

Mod on _id not allowed

Thank you.

user3665192
  • 315
  • 1
  • 4
  • 8

1 Answers1

4

You cannot change the _id of an Object in a collection once it is created (it is not allowed by mongodb at all). However you could copy the full content of the object execpt of the _id and add your new _id with the ObjectId and insert it into your collection. Afterwards you can remove all the Objects where the _id is a number. It's a bit more complicated but the result is the same (and it works).

Have a look here.

Community
  • 1
  • 1
Simulant
  • 19,190
  • 8
  • 63
  • 98