StuffHappens
StuffHappens

Reputation: 6557

MongoDB how to add field assinged by another filed

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?

Upvotes: 1

Views: 43

Answers (2)

Mandeep
Mandeep

Reputation: 364

Try this one:

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

Upvotes: 1

nimrod serok
nimrod serok

Reputation: 16033

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

Upvotes: 2

Related Questions