Outline
- Get ready for your GeoJSON data
- Convert GeoJSON data to JsonArray data for importation
- Use MongoDB command line tool to import data
- Finally, import the data successfully and find them
Tutorial
1. Get ready for your GeoJSON data
GeoJSON is a format for encoding a variety of geographic data structures. A GeoJSON object may represent a geometry, a feature, or a collection of features. GeoJSON supports the following geometry types: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, and GeometryCollection.
The codes below demonstrate a simple GeoJSON file, which is constructed with 4-point features. You could copy the text and paste into your text editor and save it with the .geojson
suffix, and load the file you saved into a GIS application like QGIS or ArcMap.
1 | { |
2. Convert GeoJSON data to JsonArray data for importation
The key thing to importing GeoJSON data into Mongodb is the file conversion from GeoJSON to JsonObject or JsonArray. In addition, there are a lot of ways to do so, but, I want to tell you the best way by using a tool called jq
. ( jq Official Website here!)
When you finish your download, you could do the conversion by using the command below. Importantly, you must put your own configuration text to replace the text between the square brackets and remove the square brackets finally. Then, try it yourself.
1 | jq --compact-output ".features" '[Your GeoJSON File]' > '[GeoJSON File converted]' |
3. Use mongodb command line tool to import data
In this step, you should check your system environment config and make sure the MongoDB client or command line tools have been installed well firstly. Then, you could use the command below and replace the content between square brackets as you do well in the previous step.
1 | mongoimport -u '[Your MongoDB User]' --password '[Your Password]' --db '[Database to Import]' -c '[Collection to Import]' --file '[Path to Your GeoJSON File]' --jsonArray '[MongoDB Connection String]' |
Here is the positive result that tells you which MongoDB has been connected and how many documents have been imported.
1 | connected to: mongodb://*********** |
4. Finally, import the data successfully and find them
Use MongoDB Client to find or query the data from the collection you have created. And, here is the result.
References & Documentations
GeoJSON Documentation
https://geojson.org/geojson-spec
MongoDB geospatial
https://www.mongodb.com/docs/manual/geospatial-queries/#std-label-geospatial-geojson
jq-tools Offical Website
https://stedolan.github.io/jq/
Author: 徐奕峰 Eephone Xu