Mongodb - return an array of _id of all updated documents

Viewed 415

I need to update some documents in one collection, and send an array of the _ids of the updated documents to another collection.

Since update() returns the number of updated items not their ids, I've come up with the following to get the array:

var docsUpdated = [];
var cursor = myCollection.find(<myQuery>);
cursor.forEach(function(doc) {
  myCollection.update({_id : doc._id}, <myUpdate>, function(error, response){
    docsUpdated.push(doc._id);
  });
});

Or I could do:

var docsUpdated = myCollection.distinct("_id", <myQuery>);
myCollection.update(<myQuery>, <myUpdate>, {multi : true});

I'm guessing the second version would be faster because it only calls the database twice. But both seem annoyingly inefficient - is there another way of doing this without multiple database calls? Or am I overcomplicating things?

1 Answers
Related