Home > Software design >  MongoDB inserts field names as string instead of getting the value
MongoDB inserts field names as string instead of getting the value

Time:04-29

I want to create a new location field from already existing longitude and latitude.

db.neigborhood.updateMany({}, {
$set: {
    "location": {
        "type": "Point",
        "coordinates": ["$longitude", "$latitude"]
    }   
}});

I wrote this code that should create the new field, but the problem is that instead of the field values I get the names as strings.

{
  "_id": {
    "$oid": "626a01f1df85b4b2937ece2d"
  },
  "latitude": "10.4980067",
  "longitude": "-66.8335096",
  "location": {
    "type": "Point",
    "coordinates": [
      "$longitude",
      "$latitude"
    ]
  }
}

What am I doing wrong that I get "$longitude" instead of the -66.8335096 value?

CodePudding user response:

Works with Update with Aggregation Pipeline.

db.neigborhood.updateMany({},
[
  {
    $set: {
      "location": {
        "type": "Point",
        "coordinates": [
          "$longitude",
          "$latitude"
        ]
      }
    }
  }
])

Sample Mongo Playground

  • Related