Search code examples
mongodbmongodb-querymongo-shellmongodb-update

Update all documents in a collection in Mongodb with a new field


I have a collection named employees with documents like.

{
first_name:"john",
last_name:"doe"
}

I want to run an update query which adds a new field like {name:'john doe'}

I know it can be done like this

db.employees.find({}).forEach(doc=>db.employees.update({"_id":doc._id},{$set:{name:doc.first_name+"-"+doc.last_name}}))

but its taking a lot of time when i am using mongo compass with db running in atlas.


Solution

  • Here's one way you could do it by using an update aggregation pipeline.

    db.employees.update({
      "first_name": {"$exists": true},
      "last_name": {"$exists": true},
      "name": {"$exists": false}
    },
    [
      {
        "$set": {
          "name": {
            "$concat": ["$first_name", " ", "$last_name"]
          }
        }
      }
    ],
    {"multi": true}
    )
    

    Try it on mongoplayground.net.