Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

$concat for one field in mongosh updateOne method

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading