[SOLVED] - Copying a value to another doc field in one line

To do a backup inside the same collection document I do:

_.each(MyCollection.find({something: true}).fetch(), function(doc) {
  MyCollection.update({doc._id}, {$set: {backup: doc.content}});
});

Is it possible to copy a value to another doc field in one line without fetching the document first ?
Example:

MyCollection.update({something: true}, {$set: {backup: $content}}, {multi: true});

You can do this most efficiently using rawCollection(). The trick is to use the aggregation pipeline available starting with MongoDB 4.2:

Find and Update a single document

setCurrentValue: (id, newValue) => {
  return myCollection.rawCollection().findOneAndUpdate(
      { _id: id },
      [
        { $set: {previousValue: "$currentValue", currentValue: newValue} }
      ],
      { projection: {_id: 1}, returnDocument: 'after'}
    )
  }

Find and Update multiple documents

updateMany() should work using the Aggregation pipeline

2 Likes