Working with MongoDB and GeoJSON

What is MongoDB

“MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling.

A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.”

http://docs.mongodb.org/manual/core/introduction/

What is GeoJSON

GeoJSON is a format for encoding a variety of geographic data structures.

– http://geojson.org

GeoJSON allows storing geographic data as Points, LineString, Polygon and many more formats. Each geometric information can be enriched with properties and is then called a Feature

{ 
    "type": "Feature",
    "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
    "properties": {"someproperty": "somevalue"}
}

These features again can be grouped into collections, called FeatureCollection

Combine best of both worlds

Working with GeoJSON and MongoDB in NodeJS works very simple, because MongoDBs JSON-like documents allow us to store GeoJSON as is.

A short example using the mongoose for MongoDB would look like the following.
(Attention: this example is shortened and missing some boilerplate code)

var GeojsonfeatureSchema = new Schema({
    type: {type: String},
    'geometry' : {
        type: {type: String},
        'coordinates' : {
            'type' : [Number],
            'index' : '2dsphere',
            'required' : true
        }
    },
    'properties' : {
        'speed' : Number,
        'measurement' : Number,
        'quality' : String
    }
});

mongoose.model('GeojsonFeature', GeojsonfeatureSchema);
var GeojsonFeature = mongoose.model('GeojsonFeature');

new GeojsonFeature({
    'type' : 'Feature',
    'geometry' : {
        'type' : 'Point',
        'coordinates' : [50.2, 9.7],
    },
    'properties' : {
        'speed' : 10
        'measurement' : 9.06
        'quality' : "very bad"
    }
}).save(function(err, doc) {
 //...
));

Create an index and query geo data

After storing data in our database, it is now about time to think about how to get data out of the database again. Because we are working with geo data, it would be nice to retrieve data in a “show me all entries near a certain coordinate” way. So let’s find a way to do this.
An index over the coordinates in our document collection was automatically created because we added the property 'index' : '2dsphere'. See details about these indexes here.

Because MongoDB is awesome, it now lets us query our data in a very intuitiv way, creating queries like this:

Find all data near a coordinate

Note: GeoJSON defines the first of the coordinates to be longitude!

var query = {
    'coordinates' : {
        $near: {
        $geometry: {
             type: "Point" ,
             coordinates: [ lng , lat ]
        },
        $maxDistance: distance,
        $minDistance: 0
        }
    }
};
Geojson.find(query, '-__v -_id', function(err, doc) {
    //hooray we've got our documents 
});

Find all data in a given bounding box

var query = {
    'geometry.coordinates': {
        $geoWithin: {
            $box: [
                [ swlng, swlat ],
                [ nelng , nelat ]
            ]
        }
    }
};
Geojson.find(query, '-__v -_id', function(err, doc) {
    //hooray we've got our documents 
});

That’s all about that. No complex calculations, just some simple queries 🙂

2 comments

  1. Pingback: Visualising collected data with Leaflet | RoadStar
  2. dineshramitc · July 27, 2015

    Reblogged this on Dinesh Ram Kali..

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s