Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Last active August 29, 2015 14:03
Show Gist options
  • Save saintc0d3r/105c9f85e04686ab808b to your computer and use it in GitHub Desktop.
Save saintc0d3r/105c9f85e04686ab808b to your computer and use it in GitHub Desktop.
Geospatial Spherical Index in MongoDb
// Let's say , we have a geo database that has places collection in it
use geo
db.places.insert({'name': 'pepito', 'city': 'Badung, Bali', 'type': 'retail', 'location': {'type': 'Point', 'coordinates': [-8.738151,-25.1735585]}})
db.places.insert({'name': 'circle-k', 'city': 'Tuban, Bali', 'type': 'mini mart', 'location': {'type': 'Point', 'coordinates': [-8.7358627,-25.168867000000006]}})
db.places.insert({'name': 'ayunadi', 'city': 'Tuban, Bali', 'type': 'grocery', 'location': {'type': 'Point', 'coordinates': [-8.7394041,-25.1675752]}})
// Next, we'll put '2dsphere' index on the location field
// Caution: 2dsphere is limited to the range -180,180 for x coordinate/longitude, and -90,90 for y coordinate/latitude !
var index = {'location':'2dsphere', 'type':1, 'city':1}
db.places.ensureIndex(index)
db.places.getIndexes()
// supposed, my curret location's coordinate is -5,-20. I want to go to the nearest store to buy some foods & drinks.
// Suggest me nearest store (within 20000000 meters) to my current location
var my_current_location = { $geometry: { 'type': "Point", 'coordinates': [-5,-20]}, $maxDistance: 20000000 }
var query = {'location':{$near: my_current_location}}
var result = db.places.find(query).limit(1)
result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment