2012-11-08 36 views
1

我在使用MongoDB/Rails查詢地理空間索引時遇到了問題。 我使用這種寶石 - https://github.com/kristianmandrup/mongoid_geospatial在rails中使用geoNear/Mongoid

這裏是我相當基本的模式:

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}) 

然而,這沒有返回預期結果(即它從全國各地返回東西,而不僅僅是在那個特定的lon/lat附近)

另外,我將如何去做一個ge在這附近?
這樣我就可以找回每個結果中心點的距離?

注意 寫完這個問題後,我已經看到寶石已經更新,但我不知道是否有更好的選擇..?

回答

4

您不需要mongoid_geospatial寶石來做geoNear查詢:mongoidalready supports it(在版本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)