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",
}