Home > Enterprise >  $concat for one field in mongosh updateOne method
$concat for one field in mongosh updateOne method

Time:04-30

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 [email protected], I want to update it to become [email protected]___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.

CodePudding user response:

Use Update with Aggregation Pipeline.

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

Sample Mongo Playground

  • Related