Search code examples
mongodbobjectid

Generating a new Mongo object id for each document in a collection?


How do you go about creating a unique object id for each document in a mass update?

I've tried,

db.foo.update({ objectId: null }, { $set: { objectId: new ObjectId() }}, { multi: true })

But that gives me the same object id for each document.


Solution

  • Because you're applying a unique value to each doc, you need to iterate over your collection and update the docs one at a time.

    In the shell:

    db.foo.find({ objectId: null }).forEach(function(doc) {
        doc.objectId = new ObjectId();
        db.foo.save(doc);
    });