Ruby on rails Mongoid,以公里为单位获取与模型的距离

Ruby on rails Mongoid,以公里为单位获取与模型的距离,ruby-on-rails,ruby,mongoid,Ruby On Rails,Ruby,Mongoid,我有一个模型商店,它有一个用于地理定位的字段: class Shop include Mongoid::Document field :location, type: Array index( { location: '2d' }, { min: -180, max: 180 }) before_save :fix_location, if: :location_changed? def fix_location self.location = self

我有一个模型商店,它有一个用于地理定位的字段:

 class Shop
   include Mongoid::Document
   field :location, type: Array

   index( { location: '2d' }, { min: -180, max: 180 })
   before_save :fix_location, if: :location_changed?
   def fix_location
    self.location = self.location.map(&:to_f)
   end
 end
我已经为我的模型创建了索引

然后我想找50公里左右的商店:

  distance = 50 # km
  loc = [lat, lng]

  Shop.where(location: {"$near" => loc , "$maxDistance" => distance.fdiv(111.12)})
这种方法工作得很好,并给出了我需要的模型。但是,如何确定它们离我的位置有多远(以公里为单位)


是否需要使用聚合?

由于MongoDB$near操作符已经按距离对文档进行了排序,因此您只需在Rails服务器中计算查询返回的每个文档的距离,例如使用

请注意纬度和经度的交换,因为MongoDB希望2D geo数组的格式为[经度,经度],而Haversine gem同样需要[经度,经度]

distance = 50 # km
loc = [lat, lng]
loc_lng_lat = [lng, lat]
Shop.where(location: {"$near" => loc_lng_lat , "$maxDistance" => distance.fdiv(111.12)}).each do |shop|
    shop_lat_lng = [shop.location[1], shop.location[0]]
    distance = Haversine.distance(loc, shop_lat_lng)
    # do what you want with the distance
end