Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Last active August 29, 2015 14:03
Show Gist options
  • Save saintc0d3r/b309be49c3482f9e71e4 to your computer and use it in GitHub Desktop.
Save saintc0d3r/b309be49c3482f9e71e4 to your computer and use it in GitHub Desktop.
Geospatial Index In Mongodb
// Let's say , we have a geo database that has places collection in it
use geo
db.places.insert({'name': 'pepito', 'type': 'dept. store', 'location': [40, 70]})
db.places.insert({'name': 'circle-k', 'type': 'mini mart', 'location': [40.232, -74.343]})
db.places.insert({'name': 'ayunadi', 'type': 'grocery', 'location': [41.232, -75.343]})
// Next, we want to put an index on the location field.
// Since the location's value is the x-y coordinate of a place, we'll put '2d' index on it.
var index = {'location': '2d', 'type':1}
db.places.ensureIndex(index)
db.places.getIndexes()
// Let's test it using this following case:
// supposed, my curret location's coordinate is 50,50. I want to go to the nearest store to buy some foods & drinks.
// Suggest me nearest store to my current location
var my_current_location = [50,50]
var query = {'location':{$near: my_current_location}}
var result = db.places.find(query).limit(1)
result
// Explain the result. Notice the cursor, milis, nscanned
result.explain
// Now, let's drop the compound index and re-invoke the query
db.places.dropIndex(index)
db.places.find(query).limit(1)
// You'll get an error, my friends :D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment