MongoDB Geospatial

MongoDB provide for geographica data support, which means you can store geographic data and use command query to find out information about those data, e.g query the nearest geo data store in a collection that’s near a specified longitude and latitude.

To be able to a query like that, the document will need contain some coordinate information and a index need to created on those coordinates. MongoDB support the following indexes:

  • 2d Index - This is for legacy coordinate pairs, shold be avoid.
  • 2d Sphere Index - Calculation on earth like sphere (Earth ellipsoid), support GeoJSON objects data format.
  • Geo Haystack - Optimised for query on very small areas.

GeoJSON

This is essentially encoding variety of geographic data data in JSON format, the spec is very simple and easy to interpret.One thing to look out for the way it represent coordinates, it use (longitude, latitude) instead of (latitude, longitude) that some people used to.

At the moment it support the following geometry types:

  • Point
  • MultiPoint
  • LineString
  • MultiLineString
  • Polygon
  • MultiPolygon
  • GeometryCollection - This will contain a collection of mixture of geometries.
  • Feature - It will contain geometry information and any other valid JSON.
  • FeatureCollection

There is a very website that will help you validate GeoJSON data - GeoJSON Lint, it will check if your GeoJSON is syntatically correct and render the geometries on a map, so you can see the location to double confirm it. Here are some examples of different GeoJSON types:

  • {
        "type": "Point",
        "coordinates": [
            -2.42222,
            51.42222
        ]
    }
    			
  • {
        "type": "Feature",
        "geometry": {
            "type": "LineString",
            "coordinates": [
                [
                    -2.2222,
                    51.11111
                ],
                [
                    -4.44444,
                    51.11111
                ]
            ]
        },
        "properties": {
            "name": "a line"
        }
    }
    			

Data

Get data into MongoDB

Geospatial Query

Way to query geospatial data within MongoDB

Inclusive

This is using the $geoWithin operator, normally you’ll pass in a polygon. e.g: find all locations within the a certain boundry created by Polygon.

Intersection

Perform by $geoIntersects operator, it will query for locations that intersect with a specified GeoJSON object

Proximity

Query for point closest to the defined query point and the results are sorted by distance, the $near operator is used.

Radius

Its also possible to query all points thats within certain radius of a define point. The $geoWithin operator is used.