Home > Enterprise >  How to update a specific field in all MongoDB documents from a string value to an array value
How to update a specific field in all MongoDB documents from a string value to an array value

Time:10-28

My MongoDB collection contains 83,000 documents which were imported from a .csv file. The schema is a simple, non-nested one. Each document has a 'coordinates' field of type String which is like

coordinates: "61.11736,-149.86379"

I want to update/replace all of their values to be like: coordinates: [61.11736, -149.86379] because I want to use the MongoDB $near query selector as it only works with fields of type: 'Point' with <field_name>: [<long>, <lat>].

What sort of query should I run to perform this update? (I'm using Node.js/Express). Thanks in advance.

I basically want to make a query that will get places (which are MonogoDB documents) that are near a specified set of coordinates: [long, lat] but I'm not able to do so.

CodePudding user response:

You can perform an update with an aggregate pipeline to make convert the field into a GeoJson point object.

db.geoJson.update({},
[
  {
    "$addFields": {
      "coordinates": {
        type: "Point",
        coordinates: {
          "$map": {
            "input": {
              "$reverseArray": {
                "$split": [
                  "$coordinates",
                  ","
                ]
              }
            },
            "as": "c",
            "in": {
              "$convert": {
                "input": "$$c",
                "to": "double",
                "onError": "",
                "onNull": ""
              }
            }
          }
        }
      }
    }
  }
],
{
  multi: true
})

Mongo Playground

Afterwards, you can create 2d sphere index on the field coordinates to perform the $near query you want.

Note that the coordinates are swapped to cater to Fix potential “longitude/latitude is out of bounds” error when creating the 2dsphere Index.

Ref: https://database.guide/fix-longitude-latitude-is-out-of-bounds-in-mongodb-when-creating-a-2dsphere-index/

  • Related