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".
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"
]
}
}
}
])