Importing a Shapefile into MongoDB using GeoJSON
Shapefiles are technology from the past when desktops ruled supreme.
Majority of map-related data provided by government agencies is in the form of geospatial vector data stored in a semi-proprietary and complex format known as a Shapefile.
Shapefiles are technology from the past when desktops ruled supreme. Nowadays, developers want a simpler way to access data.
It is not a snap, importing a Shapefile (a file containing geospatial vector data) into a document-oriented database.
Step 1:
We will use ogr2ogr
to convert a Shapefile to GeoJSON.
$ brew install goal
$ ogr2ogr -f GeoJSON -t_srs crs:84 file_name.geojson file_name.shp
-t_srs cos:84 option ensures that the right projection is being rendered and that GPS coordinates are properly encoded.
Step 2:
We will use mongoimport
to import the file into MongoDB.
mongoimport --db dev -c points --file "file_name.geojson" --jsonArray
--jsonArray
tells mongoimport to expect an array of objects so we might have to open the Shapefile and pull out the “features” array.
Alternatively we can use --type json
option instead:
mongoimport --db dev -c points --file "file_name.geojson" --type json
Step 3:
To make the data queryable we have to add a 2dsphere
index to the field that contains geometry information. In our case the field was actually named “geometry.”
"geometry": {
"type": "LineString",
"coordinates": [
[-122.466597727410203, 37.72592447531234],
[-122.466538207925268, 37.726008134595659],
[-122.466545014733939, 37.726092655875313],
[-122.46662269919527, 37.726149395842484],
[-122.466715781686247, 37.726165938701818],
[-122.466832802132004, 37.726142308565606],
[-122.466897677698299, 37.72606137786606],
[-122.466866500919124, 37.7259772625764],
[-122.466740909948271, 37.725929815795403],
[-122.466597727410203, 37.72592447531234]
]
}
db.sfsweeproutes.ensureIndex({"geometry":"2dsphere"})
Step 4:
Let’s have fun!
db.sfsweeproutes.find({geometry:{ $near :{$geometry: { type: "Point", coordinates:[ -122.46654501473394, 37.72609265587531 ] },$minDistance: 0, $maxDistance: 10}}})
Subscribe to The infinite monkey theorem
Get the latest posts delivered right to your inbox