Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Update field using value from another field

Using Mongo shell, I am trying to add a field which has the same value as an existing field for all documents in a collection. Assuming we have two documents :

{
   'foo': 'str1'
}

and

{
   'foo': 'str2'
}

I would like to insert a new field 'foo_new' which has the respective value of 'foo' as its value, so that the documents become

{
   'foo': 'str1'
   'foo_new': 'str1'
}

and

{
   'foo': 'str2'
   'foo_new': 'str2'
}

The command I use to update the collection ('coll' say) in Mongo shell is

db.coll.update({}, {$set: {'foo_new': '$foo'}}, {multi: true})

The result of running this command are the two updated documents

{
   'foo': 'str1'
   'foo_new': '$foo'
}

and

{
   'foo': 'str2'
   'foo_new': '$foo'
}

i.e. '$foo' is being interpreted as a literal for some reason.

like image 989
John S. Avatar asked Mar 24 '26 08:03

John S.


1 Answers

Try this snippet:

db.<collection>.update({}, [{$set: {'foo_new': '$foo'}}], {"multi": true})

Note the [] square brackets in 2nd argument. More info: https://stackoverflow.com/a/37280419/4050261

like image 98
Basu_C Avatar answered Mar 27 '26 05:03

Basu_C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!