In MongoDB, is it possible to update the value of a field using the value from another field? The equivalent SQL would be something like:
UPDATE Person SET Name = FirstName + ' ' + LastName
And the MongoDB pseudo-code would be:
db.person.update( {}, { $set : { name : firstName + ' ' + lastName } );
Best Answer
The best way to do this is in version 4.2+ which allows using of aggregation pipeline in the update document and the
updateOne
,updateMany
orupdate
collection methods. Note that the latter has been deprecated in most if not all languages drivers.###MongoDB 4.2+
Version 4.2 also introduced the
$set
pipeline stage operator which is an alias for$addFields
. I will use$set
here as it maps with what we are trying to achieve.Note that square brackets in the second argument to the method which define an aggregation pipeline instead of a plain update document. Using a plain document will not work correctly.
###MongoDB 3.4+
In 3.4+ you can use
$addFields
and the$out
aggregation pipeline operators.Note that this does not update your collection but instead replace the existing collection or create a new one. Also for update operations that require "type casting" you will need client side processing, and depending on the operation, you may need to use the
find()
method instead of the.aggreate()
method.##MongoDB 3.2 and 3.0 The way we do this is by
$project
ing our documents and use the$concat
string aggregation operator to return the concatenated string. we From there, you then iterate the cursor and use the$set
update operator to add the new field to your documents using bulk operations for maximum efficiency.###Aggregation query:
###MongoDB 3.2 or newer
from this, you need to use the
bulkWrite
method.###MongoDB 2.6 and 3.0
From this version you need to use the now deprecated
Bulk
API and its associated methods.###MongoDB 2.4