Search code examples
javascriptnode.jsmongodbmeteor

How to perform Bulk Upsert


I'm trying to perform a Bulk Upsert for documents. I understand this can't be done natively in Meteor:Mongo and that the Node MongoDB lib has to be used with rawCollection instead.

I have the following

const bulkUpserts = [];
for (let doc of docs) {

  bulkUpserts.push({
    updateOne: {
      filter: {
        fizz: doc.buzz
      },
      update: doc,
      upsert: true,
      setOnInsert: {
        "foo": "bar",
        "createdBy": Meteor.userId(),
        "createdDate": new Date()
      }
    }
  });
}

Collection.rawCollection().bulkWrite(bulkUpserts);

The issue with ^ is that the setOnInsert doesn't seem to work. My foos aren't being set. Looks like setOnInsert isn't available as an option for updateOne. What's the alternative though? I surprisingly cannot find a way to do this in Meteor yet.

Thanks!


Solution

  • I ended up using

    const bulk = LineItems.rawCollection().initializeUnorderedBulkOp();
    
    for (let doc of docs) {    
      bulk.find({
        fizz: doc.buzz
      }).upsert().updateOne({
        $set: doc,
        $setOnInsert: {
          _id: Random.id(),
          "foo": "bar",
          "createdBy": Meteor.userId(),
          "createdDate": new Date()
        }
      });
    }
    bulk.execute().then().catch(error => console.error(error));