How to query a point(latitude, longitude) from polygons ?

248 views
Skip to first unread message

dede nerde

unread,
Nov 21, 2015, 8:27:45 AM11/21/15
to mongodb-user


Hello,

I have list of city objects and keep the location as string in WKT format. I want to query a point from the cities.

Regards

Wan Bachtiar

unread,
Nov 29, 2015, 10:27:57 PM11/29/15
to mongodb-user

Hi Dede,

As of MongoDB v3.2, there is no server side support for WKT geometries. I could not find an existing feature request for this, you may want to raise one on MongoDB JIRA SERVER project.

Currently you would have to convert WKT strings either into GeoJSON or legacy coordinates pair format beforehand. There are various third party converters out there, for example in Python you can use geojson library and shapely library to convert WKT into geojson:

import geojson
import shapely.wkt
s = '''POLYGON((-181 -30, -190 -30, -190 -50, -181 -50, -181 -30))'''
g1 = shapely.wkt.loads(s)
g2 = geojson.Feature(geometry=g1, properties={})
g2.geometry

You can store the converted result in the same document, i.e. :

{
    city: "foobar", 
    wkt: "POLYGON((-181 -30, -190 -30, -190 -50, -181 -50, -181 -30))",
    geojson: {
        "type": "Polygon",
        "coordinates": [
                [ 
                    [-181,-30], 
                    [-190,-30], 
                    [-190,-50], 
                    [-181,-50], 
                    [-181,-30]
                ]
            ]
        }
}

Then create a geospatial 2dsphere index for GeoJSON-formatted data by using db.collection.createIndex() on the collection. A 2dsphere index supports queries that calculate geometries on an earth-like sphere.

For example:

/* Create a 2dsphere index on 'geojson' field */
db.cities.createIndex({ geojson: "2dsphere"});

After the index creation, you can use geospatial query operators such as $near, $nearSphere, $geoWithin, and $geoIntersects on the field.

Also please check out MongoDB Geospatial Tutorial for examples and more information on geospatial.


Regards,

Wan.


Reply all
Reply to author
Forward
0 new messages