How can I add a new field from another one value?

Viewed 189

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).

2 Answers

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

Related