skip to Main Content

I have a collection in MongoDb someCollection containing field field1.
I want to add another field with values equal to field1. I do it like this:

db.someCollection.updateMany({}, {$set:{"newField": "$field1"}})

But the after update I got row like this

{"field1": "value1", "newField": "$field1"}

But expected result is:

{"field1": "value1", "newField": "value1"}

What is wrong?

2

Answers


  1. You can use update with pipeline. It looks almost the same, but the second part uses []:

    db.someCollection.updateMany({}, [{$set:{"newField": "$field1"}}])
    

    See how it works on the playground example

    Login or Signup to reply.
  2. Try this one:

    db.someCollection.updateMany({}, [{$set:{"newField": {$expr: {$field: "field1"}}}]})
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search