MongoDB有一个非常好的
Geospatial Indexing功能.如何在Mongoid的Rails中使用它?
解决方法
您可以在mongoid中定义这样的地理索引
class Item include Mongoid::Document field :loc,:type => Array index( [ [:loc,Mongo::GEO2D] ],background: true ) end
和查询
$near命令(不带maxDistance)
location = [80.24958300000003,13.060422] items = Item.where(:loc => {"$near" => location})
$near命令(带maxDistance)
distance = 10 #km location = [80.24958300000003,13.060422] items = Item.where(:loc => {"$near" => location,'$maxDistance' => distance.fdiv(111.12)})
使用km时转换距离为111.12(一度约为111.12公里),或者使用距离离开距离
$centerSphere / $nearSphere查询
location = [80.24958300000003,13.060422] items = Item.where(:loc => {"$within" => {"$centerSphere" => [location,(distance.fdiv(6371) )]}})
这将找到10公里半径内的物品.在这里,我们需要转换距离/ 6371(地球半径)以使其与km一起工作.
first_loc = [80.24958300000003,13.060422] second_loc = [81.24958300000003,12.060422] items = Item.where(:loc => {"$within" => {"$Box" => [first_loc,second_loc]}})
这将帮助您找到给定边框内的项目.