【问题标题】:Using geoNear with Rails / Mongoid将 geoNear 与 Rails / Mongoid 一起使用
【发布时间】:2012-10-28 16:29:31
【问题描述】:

我在使用 MongoDB/Rails 查询地理空间索引时遇到问题。 我正在使用这个 gem - https://github.com/kristianmandrup/mongoid_geospatial

这是我相当基本的模型:

class Company
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Geospatial

  field :name, type: String

  field :location, type: Array, spatial: true

  spatial_index :location

  validates :location, location: true
end

然后,在我的控制器中,我有这个

    #@vendors = Vendor.where(:location.near => {:point => [-2.1294761000000335,57.0507625], :max => 5})

但是,这并没有返回预期的结果(即,它从各地返回东西,而不仅仅是在特定的经度/纬度附近)

另外,我将如何使用这个进行 geoNear?
这样我就可以取回每个结果与中心点的距离?

注意 写完这个问题后,我看到 gem 已经更新了,但我不确定是否有更好的选择..?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid geospatial


    【解决方案1】:

    您不需要 mongoid_geospatial gem 来执行 geoNear 查询:mongoid 已经支持它(至少在版本 3 中)。

    将您的模型更改为:

    class Company
      include Mongoid::Document
      include Mongoid::Timestamps
    
      field :name, type: String
    
      field :location, type: Array
    
      index({location: "2d"})
    
      validates :location, location: true
    end
    

    并将您的查询运行为:

    @vendors = Vendor.geo_near([-2.1294761000000335,57.0507625]).max_distance(5)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 2012-11-18
      • 2013-02-19
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多