Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k points)

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 } );

1 Answer

0 votes
by (106k points)

To update the MongoDB field using the value of another field for version 4.2 also introduced the $set pipeline stage operator which is an alias for $addFields. You can use $set here as it maps with what we are trying to achieve.

db.collection.<update method>( 

    {},

    [ 

       {"$set": {"name": { "$concat": ["$firstName", " ", 

       "$lastName"]}}}

 

     ]

 

)

Related questions

0 votes
2 answers
asked Sep 13, 2019 in SQL by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...