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

db.monuments.save({"name": "Mole Antonelliana", loc : { type: "Point", coordinates: [ 7.693160499999976, 45.06905210000001 ] }})

db.monuments.save({"name": "Duomo di Torino", loc : { type: "Point", coordinates: [ 7.684594000000061, 45.0736459 ] }})

db.monuments.save({"name": "Museo Egizio, loc : { type: "Point", coordinates: [ 7.684304099999963, 45.0684296 ] }})

db.monuments.save({"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”

db.monuments.ensureIndex({loc:"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

comments powered by Disqus

cloudparty

Follow Us