ruby on rails - Sort MongoDB documents by their distance to a given point -


i have mongodb collection. each document in collection has x,y coordinations representing position on grid. given point (x',y') retrieve top k documents position closest (x',y') euclidean distance. i'm using mongodb rails app. calculation on db if it's possible. how can it?

if store coordinates array [x, y], need create geospatial index ("2d") on field.

to query index:

db.runcommand({geonear: <collection>, near: [x, y], limit: k}) 

if on mongodb 2.4, preferred way use geojson format (i.e. {type: "point", coordinates: [x, y]}) , "2dsphere" index, legacy format supported.

to query index:

db.runcommand({geonear: <collection>, near: {type: "point", coordinates:[x, y]}, limit: k}) 

the geonear command returns results ordered distance.

here documentation:


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -