Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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.

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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top