I have a collection of, for example FieldA (string), FieldB (string). I now want to update the entire collection, such that FieldB gets set to the result of passing FieldA of the same document to a transform function, ie, something like this:
updateMany({}, ['$set': {'FieldA': myTransform('$FieldB')}])
where myTransform is a JavaScript Function. In my case, it would simply convert the string-value of FieldA to integer, as to get rid of potential leading 0s.
Obviously, this does not work: It would simply call myTransform with a constant argument of '$myField', not the actual value of the field in the current document.
How can I change this query to efficiently do what I want, ie set a field of the currently considered document to a mapped value of another field on the same document? Do I absolutely have to write two queries, one to get the values, and one to update them?
Thanks!
You can replace your js function with $toInt in an aggregation function. After populating FieldA by $addFields, use $merge to update back to your collection.
db.collection.aggregate([
{
"$addFields": {
"FieldA": {
$toInt: "$FieldB"
}
}
},
{
"$merge": {
"into": "collection",
"on": "_id",
"whenMatched": "replace"
}
}
])
Here is the Mongo playground for your referenc.