Saturday 21 February 2015

mongoDB : Geospatial Indexes

MongoDB offers a number of indexes and query mechanisms to handle geospatial information.

Let’s say I had below data.
db.address.insert({"name": "college", "coordinates" : [15, 47]})
db.address.insert({"name": "hospital", "coordinates" : [45, -37]})
db.address.insert({"name": "office", "coordinates" : [-10, -7]})
db.address.insert({"name": "bus stop", "coordinates" : [55, 10]})
db.address.insert({"name": "airport", "coordinates" : [105, -97]})
db.address.insert({"name": "coffee shop", "coordinates" : [50, 49]})
db.address.insert({"name": "ground", "coordinates" : [150, 47]})
db.address.insert({"name": "ptr", "coordinates" : [1500000, 4700000]})
db.address.insert({"name": "shopping complex", "coordinates" : [18, 49]})

> db.address.find()
{ "_id" : ObjectId("54ccd98348a1970638dc99d2"), "name" : "college", "coordinates" : [ 15, 47 ] }
{ "_id" : ObjectId("54ccd98348a1970638dc99d3"), "name" : "hospital", "coordinates" : [ 45, -37 ] }
{ "_id" : ObjectId("54ccd98348a1970638dc99d4"), "name" : "office", "coordinates" : [ -10, -7 ] }
{ "_id" : ObjectId("54ccd98348a1970638dc99d5"), "name" : "bus stop", "coordinates" : [ 55, 10 ] }
{ "_id" : ObjectId("54ccd98448a1970638dc99d6"), "name" : "airport", "coordinates" : [ 105, -97 ] }
{ "_id" : ObjectId("54ccd98448a1970638dc99d7"), "name" : "coffee shop", "coordinates" : [ 50, 49 ] }
{ "_id" : ObjectId("54ccd98448a1970638dc99d8"), "name" : "ground", "coordinates" : [ 150, 47 ] }
{ "_id" : ObjectId("54ccd98448a1970638dc99d9"), "name" : "ptr", "coordinates" : [ 1500000, 4700000 ] }
{ "_id" : ObjectId("54ccd98548a1970638dc99da"), "name" : "shopping complex", "coordinates" : [ 18, 49 ] }
>

Create 2d Index on field coordinates
By default, a 2d index assumes longitude and latitude and has boundaries of -180 inclusive and 180 non-inclusive. If documents contain coordinate data outside of the specified range, MongoDB returns an error.
> db.address.ensureIndex({"coordinates" : "2d"})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}


Get nearest 3 locations to coordinates [40, 40]
> db.address.find({"coordinates" : {$near : [40, 40]}}).limit(3)
{ "_id" : ObjectId("54ccd9fb48a1970638dc99e0"), "name" : "coffee shop", "coordinates" : [ 50, 49 ] }
{ "_id" : ObjectId("54ccd9fb48a1970638dc99e3"), "name" : "shopping complex", "coordinates" : [ 18, 49 ] }
{ "_id" : ObjectId("54ccd9fa48a1970638dc99db"), "name" : "college", "coordinates" : [ 15, 47 ] }

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment