The Coding Notebook
Memorable coding moments of a software engineer
Using fields from updated document in MongoDB
Sometimes you want to update document(s) on MongoDB using fields from the updated document, this is how to do it.
  

Credit: This is taken from [this](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) SO answer.

In MongoDB 4.2 an aggregation pipeline was introduced to any of the update commands.
Say we had `users` collection with `firstName` and `lastName` fields, and now we want to add a `name` field for all documents, we can do that as follow:
``` db.users.updateMany( {}, // find criteria [{$set: {name: { "$concat": ["$firstName", " ", "$lastName"]}}}] ) ```