0

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.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Normal
  • 1,616
  • 15
  • 39

1 Answers1

1

Use Update with Aggregation Pipeline.

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

Sample Mongo Playground

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • 1
    That's it! thanks for answering, when I read the error, I thought it wants me to use the method aggregate, like `db.testme.aggregate()` – Normal Apr 29 '22 at 11:29