Home > Back-end >  MongoDB how to add field assinged by another filed
MongoDB how to add field assinged by another filed

Time:01-11

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?

CodePudding user response:

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

CodePudding user response:

Try this one:

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

  • Related