John S.
John S.

Reputation: 531

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.

Upvotes: 11

Views: 19550

Answers (1)

Basu_C
Basu_C

Reputation: 410

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

Upvotes: 22

Related Questions