11

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.

7
  • Does this answer your question? how to update a number field using another number field in MongoDB Commented Feb 28, 2020 at 15:36
  • @whoami: In theory it does. It's exactly what I tried, but my Mongo shell would interpret the "$a" as the string '$a' not as 2, the value of the field whose key is 'a'. Commented Feb 28, 2020 at 17:01
  • 2
    S : There is a difference in what you've tried with what has to be done, .update() should be in aggregation pipeline :: [ ] not as an object !! What is your MongoDB version ? Commented Feb 28, 2020 at 17:02
  • 1
    @whoami: Thanks for pointing out! I'll take the read & write back approach, but thanks for offering to provide a query. Commented Feb 28, 2020 at 17:12
  • 1
    Thanks, @whoami-fakeFaceTrueSoul square bracket work for me Commented May 31, 2024 at 3:40

1 Answer 1

22

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

Sign up to request clarification or add additional context in comments.

5 Comments

If we have create a new document, can we have the new field auto populated with this value. Is there a way to achieve this? I will basically have a calculation based on 2 other fields. Will the calculation reflect for the new field if we add a new document?
This isn't a valid solution for Mongo 4.0.
FWIW I ran into this same issue and didn't need to add the {"multi": true} portion, just adding the square brackets around my set criteria did the trick.
Don't use update() with {"multi": true} just use updateMany() or updateOne()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.