首先需将Shapefile转换为GeojsON格式,再导入MongoDB。使用ogr2ogr命令转换:ogr2ogr -f “Geojson” output.json input.shp。然后通过mongoimport导入:mongoimport –db yourDB –Collection yourCollection –file output.json –jsonArray。最后创建2dsphere索引:db.yourCollection.createIndex({“geometry”: “2dsphere”}),即可支持地理空间查询。

要将Shapefile数据导入MongoDB,不能直接导入,需要先转换为mongodb支持的格式,比如GeoJSON。MongoDB支持地理空间数据,可通过2dsphere索引存储和查询地理位置信息。整个过程主要包括格式转换和数据导入两个步骤。
转换Shapefile为GeoJSON
Shapefile是GIS中常用的矢量数据格式,但MongoDB不支持直接读取。需使用工具将其转为GeoJSON格式,常用工具有ogr2ogr(来自GDAL库)或QGIS。
- 确保已安装GDAL工具包,大多数linux发行版可通过包管理器安装,如ubuntu执行:sudo apt-get install gdal-bin
- 使用ogr2ogr命令转换文件:
ogr2ogr -f “GeoJSON” output.json input.shp
这会将input.shp及其相关文件(.shx、.dbf等)转换为output.json - 转换后检查GeoJSON文件结构,确保包含有效的geometry字段(如Point、Polygon等)和properties属性
使用mongoimport导入GeoJSON
MongoDB提供mongoimport工具,可将JSON、csv等格式数据导入集合。
- 运行导入命令:
mongoimport –db yourDB –collection yourCollection –file output.json –jsonArray
如果GeoJSON是数组格式(以[ ]包裹多个要素),需加–jsonArray参数 - 若每个要素独立成行(每行一个JSON对象),则去掉–jsonArray,并添加–mode insert
- 确认geometry字段符合MongoDB地理空间格式要求,例如坐标顺序应为[经度, 纬度]
创建地理空间索引
导入完成后,为geometry字段创建2dsphere索引,以便执行地理查询。
- 进入mongo shell或使用mongosh:
db.yourCollection.createIndex({“geometry”: “2dsphere”}) - 创建索引后,即可使用$near、$geoWithin等操作符进行空间查询
- 例如查找某点附近10公里内的文档:
db.places.find({
“geometry”: {
“$near”: {
“$geometry”: {
“type”: “Point”,
“coordinates”: [longitude, latitude]
},
“$maxDistance”: 10000
}
}
})
基本上就这些。只要把Shapefile转成标准GeoJSON,再用mongoimport导入并建好索引,就能在MongoDB里正常使用地理数据了。注意坐标系一般应为WGS84(EPSG:4326),避免投影问题。