Geospatial in MongoDB

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

GeoJSON is an open-source format containing simple geographical features and is based on JavaScript Object Notation. It is used to format shapes in a coordinate space and multiple types are supported by MongoDB to permit storing of geospatial data. This tutorial will cover the various ways of using geospatial in MongoDB and explain the GeoJSON polygon and point types.

Prerequisite

  • MongoDB must be properly installed and configured on the local system to use geospatial in MongoDB.

What is GeoJSON

GeoJSON is an open-source program used to format shapes in a coordinate space. The geospatial community is adopting the GeoJSON spec and as a result its library support is growing in most popular programming languages.

MongoDB is designed to simplify the developers job when working with stock data by conforming to these standards. Multiple GeoJSON types are supported by MongoDB to allow for the storing of geospatial data. The examples in this tutorial will use the two main types of Polygon and Point.

Storing Geospatial Data

This section will explain how to store geospatial data in MongoDB.

Polygon Type

The polygon is the most complex of the GeoJSON types. The polygon is used to describe an area together with its outer borders as well as its inner holes, if needed.

Here is an example of a location defined as a polygon:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{
  "name": "Ninoy Aquino International Airport",
  "location": {
    "coordinates": [
      [
        [
            121.00380420684814,
            14.515791721361213
        ],
        [
            121.00728034973145,
            14.513465165268554
        ],
        [
            121.00946903228758,
            14.510307657168987
        ],
        [
            121.01315975189209,
            14.512592700428515
        ],
        [
            121.00745201110838,
            14.51811825299417
        ],
        [
            121.00380420684814,
            14.515791721361213
        ]
      ]
    ],
    "type": "Polygon"
  }
}

The above example creates an array of points that are the exterior bounds. These are needed to close the bounds so the first and last point will be equal.

Point Type

The previous section explained the more complex polygon GeoJSON type. This section will explain the basic GeoJSON Point type that represents a single specific point on a grid.

Following is an example of an object with a location field as a point:

1
2
3
4
5
6
7
{
  "name": "Subic Bay College",
  "location": {
    "coordinates": [14.8407462,120.2831914],
    "type": "Point"
  }
}

Note that the longitude’s value comes before the latitude.

Indexing GeoSpatial

In order to perform queries against the stored geospatial data, a geospatial index must be defined to the location field of the document.

Indexing via 2dsphere

The 2dsphere index works with sphere calculations that supports all of MongoDB geospatial related queries, including:

  1. Proximity
  2. Intersection
  3. Inclusion

The db.collection.createIndex() method can be used to store geospatial data in MongoDB by passing the string “2dsphere” as the index type as follows:

1
db.collection.createIndex({<location>:"2dsphere"});

Note that while the location- can be a legacy coordinate pair, a GeoJSON or the key, the “2dspher” is the type of the index.

The following example creates a 2dsphere index in the city collection:

1
2
3
4
5
6
db.city.insert(
{
  loc : { type: "Point", coordinates: [ 14.579156,120.9703558 ] },
  name: "Ocean Park Manila Philippines",
  category : "Scenery"
}

Indexing via 2d Geospatial

Two-dimensional, or 2d, indexes works with 2d calculations created for legacy coordinate pairs.

A 2d index is used in the following scenarios:

  1. When the location record as an object of GeoJSON will not be saved.
  2. If there are GeoJSON objects legacy coordinate pairs stored.

To build a geospatial 2d index, use the db.collection.createIndex() method and specify 2d. As with the 2dspher, the string “2d” is passed as the index type when using the db.collection.createIndex() method, as shown in this example:

1
db.collection.createIndex( { <location field> : "2d" } );

GeoSpatial Queries

This section will explain how to search objects against their location using geospatial queries.

The geoWithin Query

The geoWithin query allows for searching objects that exists within a specified geometry, meaning a polygon, circle or box, and is applicable to indices of 2d and 2dsphere.

Execute this query with the following syntax:

1
2
3
4
db.collection.find( { location :
                         { $geoWithin :
                            { $box|$polygon|$center : coordinates
                      } } } );

Next, the following example shows how to use the above syntax in an actual application:

1
2
3
4
5
db.city .find( { loc :
                  { $geoWithin :
                     { $box : [ [ 0 , 0 ] ,
                                [ 300 , 300 ] ]
                 } } } )

Note that the above code will query for documents within a rectangular shape polygon as defined by the details inside the $box.

Conclusion

This tutorial explained the various ways of using geospatial in MongoDB. The tutorial covered how to store geospatial data and explained the functions and uses of the polygon and point types. The tutorial also covered how to index geospatial data and perform geospatial queries in MongoDB. Remember that in order to perform queries against the stored geospatial data, a geospatial index must be defined to the location field of the document.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.