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:
- 2d index - http://docs.mongodb.org/manual/core/2d/
- 2dsphere index (2.4) - http://docs.mongodb.org/manual/core/2dsphere/
Comments
Post a Comment