3

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.

James McMahon
  • 48,506
  • 64
  • 207
  • 283

3 Answers3

5

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);
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
1

You cannot update multiple documents in a single command in MongoDb currently. You can update multiple documents with a common set of changes/updates, but you can not make unique changes to each document. You would need to create a loop to iterate over each document in the shell or your favorite programming language.

WiredPrairie
  • 58,954
  • 17
  • 116
  • 143
0

You can generate an object Id in MongoDB like this. You can iterate over your doc and use this mongo object id.

const ObjectId = require("mongodb").ObjectID;
const id = new ObjectId 
console.log(id)
Sehrish Waheed
  • 1,230
  • 14
  • 17