I want to update a particular document based on its id, I want to update the email field in this document, but I don’t want to overrite the email field completly, instead I just want to add a string beside it (concatinate it with another string), I.e. I need to 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 its 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"
]
}
}
}
])