Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

77
Views
Update field to transformed/mapped value of another field

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!