3

I have a collection "people" with documents like this one:

{
  _id: "...",
  name: "...",
  age: "..."
}

I want to perform an update to all the documents of this collection so they have an extra field "actualName" with the exact same content like "name". I have tried this:

db.people.updateMany({}, { $set { actualName: $name } })

But I get this error:

$name is not defined

I'm doing it from MongoSH (Compass).

Héctor
  • 24,444
  • 35
  • 132
  • 243
  • see this [answer](https://stackoverflow.com/a/60456319/8987128) will help, you can not use the internal field as a value to another field in a simple update query, you can try update with aggregation pipeline. and little similar [question](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field). – turivishal May 27 '21 at 17:11

2 Answers2

4

You can use something with aggregation updates

db.collection.update({},
[
  {
    "$set": {
      "actualName": "$name"
    }
  }
])

Working Mongo playground

varman
  • 8,704
  • 5
  • 19
  • 53
  • 1
    My god... I have tried all the combinations with quotes and aggregation but not this one. Thank you! – Héctor May 27 '21 at 17:14
2

Starting with Mongo 4.2, you can use aggregation pipeline with update() method to update fields with values of other fields. You can do it like this:

db.collection.update({},
[
  {
    "$set": {
      "actualName": "$name"
    }
  }
],
{
  "multi": true
})

Here is a working example: https://mongoplayground.net/p/sqZBDLGJy48

NeNaD
  • 18,172
  • 8
  • 47
  • 89