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

Reference Existing fields in Update Query MongoDB

I am trying to add a new field to my collection in MongoDB (This collection has around 40k documents) using existing fields in the document, I’m running the below update query

db.myCollection.updateMany( 
{ },
[
    { $set : { newField : "some_extra_string" + "$existingField1" + "other_extra_string" + "$existingField2" } }
])

However the newField is getting updated as

"newField" : "some_extra_string$existingField1other_extra_string$existingField2"

It’s not referencing the existing field, rather appending the string literals "$existingField1"/"$existingField2".

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

I’m using the MongoDB Documentation as my source : https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany/#example-1–update-with-aggregation-pipeline-using-existing-fields

Here in the example, they’re referencing existing fields using the dollar sign, what am I doing wrong here?

>Solution :

Currently, you are doing the string concatenation with plain text.

Instead, you need the $concat operator to concat strings with the reference field(s).

db.myCollection.updateMany({},
[
  {
    $set: {
      newField: {
        $concat: [
          "some_extra_string",
          "$existingField1",
          "other_extra_string",
          "$existingField2"
        ]
      }
    }
  }
])

Demo @ 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