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

104
Views
Update MongoDB field using a custom JavaScript function which takes values of another fields as arguments

I want update a specific field with the output of a custom JavaScript function which have arguments of another field values in document of MongoDB. This is my DB. I use MongoDB 5.0.5 version.

{
    "_id": {
        "$oid": "61bacd748364a864118dcfeb"
    },
    "time": "14:24:04",
    "lat": "6.406405",
    "lon": "27.386247",
}
{
    "_id": {
        "$oid": "61bacd748364a864118dcfec"
    },
    "time": "14:24:04",
    "lat": "6.406405",
    "lon": "27.386247",
}...

I wanted to add new fields ("lat_G" and "lon_G") which are computed with values of "lat" and "lon" in each document. So, I made a function named "placeonGrid" which needs 3 arguments. When I directly put numbers into the function, it works. However, it doesn't work when the expression for values of another fields was used. It shows "NaN". This is my code.

 db.collection(collectionName).updateMany( 
      {}, 
      [{ $set: { 
         lat_G: placeonGrid("$lat", "$lon", gridSize).lat_out, 
         lon_G: placeonGrid(6.406405, 27.386247, gridSize).lon_out } 
      }] 
 );

The result is follows.

{
    "_id": {
        "$oid": "61bacd748364a864118dcfeb"
    },
    "time": "14:24:04",
    "lat": "6.406405",
    "lon": "27.386247",
    "lat_G": NaN,
    "lon_G": "27.12345",
}
about 4 years ago · Juan Pablo Isaza
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!