Indexing geo-spatial data is a killer feature provided by MongoDb. This function, based on indexes, can be used to search the database for queries such as: Which elements are included within a given range of coordinates?

Let's have a look at some examples, showing possible uses of this function:

Imagine you are populating a collection like this{"name": "Mole Antonelliana", loc : { type: "Point", coordinates: [ 7.693160499999976, 45.06905210000001 ] }}){"name": "Duomo di Torino", loc : { type: "Point", coordinates: [ 7.684594000000061, 45.0736459 ] }}){"name": "Museo Egizio, loc : { type: "Point", coordinates: [ 7.684304099999963, 45.0684296 ] }}){"name": "Basilica di Superga", loc : { type: "Point", coordinates: [ 7.767677300000059, 45.08080229999999 ] }})

As you can see, it is a very simple collection, with a single field containing a monument name, and an object of type GeoJson (a special format provided by MongoDb for representing geometric objects)

Then, you can prepare a MongoDb index, specifying it will be of type “2dsphere”


With such command, you are indicating to the database how to perform an indexing of the data stored in "loc" field.

A possible query, making use of such mechanism, is the following:

db.monuments.find({ loc :{ $near :{$geometry : {type : "Point" ,coordinates : [7, 45] }, $maxDistance : 100}}});

This search query returns all documents next to the specified coordinates, within a maximum range of 100 metres.

With a continuously increasing number of mobile applications (and others), this function will become more and more critical. 

Antonio Pessolano

Senior Developer at Consoft Sistemi S.p.A. , Website , @apessolano , Linkedin profile
I destroyed my first computer when i was seventeen when i was trying to do a RAM upgrade. I am 33 years old now and i solve problems trying to reduce the average number of problems that i have found!

All articles by Antonio Pessolano


comments powered by Disqus


Follow Us