0

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.

2 Answers2

3

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.

rickhg12hs
  • 10,638
  • 6
  • 24
  • 42
0

Use the db.collection.updateMany() to update all documents that match a specified filter.

for example: To update all documents in the sample_airbnb.listingsAndReviews collection to update where security_deposit is less than 100:

    use sample_airbnb

db.listingsAndReviews.updateMany(
  { security_deposit: { $lt: 100 } },
  {
    $set: { security_deposit: 100, minimum_nights: 1 }
  }
)

The update operation uses the $set operator to update the value of the security_deposit field to 100 and the value of the minimum_nights field to 1.

this was taken from :https://www.mongodb.com/docs/mongodb-shell/crud/update/

Dump Eldor
  • 92
  • 1
  • 11
  • That's for adding a field with fixed values. In my case the value of the field is calculated by joining `first_name` and `last_name` . It should be something like $set:{name:"$first_name"+" "+"$last_name"} – Harsh Prakash Mar 05 '23 at 11:29