Search code examples
mongodbmongodb-querymongo-shellmongodb-update

mongosh - $concat for one field in updateOne method


I want to update a particular document for the email field based on its id, but I don't want to overwrite the email field completely. Instead, I just want to add a string beside it (concatenate it with another string), I.e. I need the current value of the email and add a string beside it.

For example, if the email field in the document was example@email.com, I want to update it to become example@email.com___deleted.

Here's what I've tried, but it's showing me an error

db.testme.updateOne({_id: ObjectId("626bc5ddd6e2abe315ff8c76")}, {$set: {$concat: {email: ['$email', '___deleted']}} })

MongoServerError: The dollar ($) prefixed field '$concat' in '$concat' is not allowed in the context of an update's replacement document. Consider using an aggregation pipeline with $replaceWith.


Solution

  • Use Update with Aggregation Pipeline.

    db.testme.updateOne({
      _id: ObjectId("626bc5ddd6e2abe315ff8c76")
    },
    [
      {
        $set: {
          email: {
            $concat: [
              "$email",
              "___deleted"
            ]
          }
        }
      }
    ])
    

    Sample Mongo Playground