3
votes

I am a mongodb noob and am running into some difficulty trying to create an equivalent to bulk save (as I can't find a bulk save operation) using the MongoDB bulk operations. Briefly, given an array of documents:

[{ _id:1, name:"a" ... }, { _id:1, name:"b" ... } ... ]

I want to bulk upsert the documents in the array, using the _id attribute as the comparison field to determine which incoming records are equivalent to records already in mongodb. In pseudo-code I want mongodb to bulk upsert as follows:

if(incomingDocument._id == existingDocument._id){
  update(incoming) // overwrite existing document with entire incoming document
} else {
  insert(incoming)
}

Ideally, I would like to pass mongo an array and an comparator vs queuing up an individual bulk operation for each document.

How/can I do this with Bulk.find().upsert().update(<update>); or similar ? (Alternately, is there an undocumented bulk save() operation?)

Thank you!

1

1 Answers

1
votes

Bulk.find.upsert

With the upsert option set to true, if no matching documents exist for the Bulk.find() condition, then the update or the replacement operation performs an insert. If a matching document does exist, then the update or replacement operation performs the specified update or replacement.

But you will need to loop over your collection:

var bulk = db.items.initializeUnorderedBulkOp();
myDocumnets.forEach(function(doc) {
  bulk.find({_id: doc._id}).upsert().replaceOne(doc);
});
bulk.execute({w: 1, j: true}, function (err, result) {
  if (result.isOk()) {
    ...
}

More, or less, I am sorry I am not able to test it at the moment. I am also not able to say how it will behave on large amounts of documents.

UPDATE

I modified code, as suggested by Colin.