Store GeoJSON polygons in MongoDB

Dominik Nöger picture Dominik Nöger · Jun 21, 2012 · Viewed 11.1k times · Source

I have the following problem with MongoDB. I got some geo data from my home country and i have to store them into mongodb to set up a simple Web Feature Service. This service will mostly do bounding box queries using the $within operator. The data is in GeoJSON format. Therefore i imported at first the Villages and Cities which are represented as points ([1,2]) in this format. No problem. Next step rivers and streets which are LineStrings and according to GeoJSON represented this way [[1,2],[3,4]]. But when importing the districts (which are in fact polygon and according to the GeoJSON specification 3 dim arrrays) i got the error geo values have to be numbers when creating the index.

db.collection.ensureIndex({"geometry.coordinates" : "2d"});

All data are valid GeoJSON, and are in plain 2d coordinates in EPSG:4326 projection.

Does anybody have an idea?

Answer

Bob Grabar picture Bob Grabar · Mar 20, 2013

With MongoDB 2.4 use the "2dsphere" index for GeoJSON Points, LineStrings and Polygons.

For example, you can create this index:

db.mycoll.ensureIndex( { loc : "2dsphere" } )

And store this LineString:

{ loc : { type : "LineString" , coordinates : [ [ 1 , 2 ] , [ 3 , 4 ] ] } }

See http://docs.mongodb.org/manual/applications/2dsphere/.