Convert two coordinates fields into a GeoJSON field in MongoDB 4.x
Let’s say you have a list of json objects that you want to import in MongoDB in order to make GeoSpatial queries on the fields longitude and latitude.
With the following format, Mongo cannot perform these queries. It needs to have a valide GeoJSON field. Multiple methods exists : legacy coordinates or a Point.
We can observe as well that the fields as in the json object is a string. When we import the data with the mongoimport tool, it won’t convert these values as floats.
First let’s import the data in a collection dvf for this example.
mongoimport -u guest -p password -d mydatabase -c dvf --file "/import.json" --type json
Once it’s done, we need to migrate our data into a more desirable format.
Two options are available:
- First the least optimum one:
We iterable over our collection and create a new field for every document found. We must not forget to convert the coordinates data to mongo decimal data. Otherwise Mongo won’t be able to create a 2dsphere index.
For like 80k documents, it can take a while to finish.
- The better option:
Let’s use mongo updates to increase performance by a large margin.
The update command require to define the collection at the update key.
At the updates key, you need to define q which represents the query selector like in a basic find() operation.
The magic happens at the u. The operation is the same as the previous example.
Each document has now a new geoloc field thats contains valid GeoJSON data.
Finally, we just need to create an index for our GeoSpatial query.
db.dvf.createIndex( { geoloc: “2dsphere” } )