0
我有兩個模型,Location
和Event
。Mongoid 2d查詢關聯模型
class Event
include Mongoid::Document
field :name, type: String
belongs_to :location
index({'location.coordinates' => '2d'}, {unique: true}) # I added this later on because I had an error when querying on location.coordinates
end
class Location
include Mongoid::Document
field :coordinates, type: Array
index({coordinates: '2d'}, {unique: true})
has_many :events
end
現在,如果我創建一個Event
與相關聯的位置
Location.create({coordinates: [40.7127837, -74.0059413]})
Event.create({name: "foo", location: Location.first})
我怎樣才能查詢附近的特定位置的事件? 我嘗試這樣做:
Event.where('location.coordinates' => {'$near' => [40.7127837, -74.0059413], '$maxDistance' => 1000.fdiv(111.12)}).first
,但它不返回任何結果,而
Location.where('coordinates' => {'$near' => [40.7127837, -74.0059413], '$maxDistance' => 1000.fdiv(111.12)}).first
返回前面創建的Location
對象。
我在做什麼錯?
我還沒有用過ruby,請參閱這裏瞭解如何製作一個使用mongo https://docs.mongodb.org/manual/reference/operator/query/nearSphere/的nearSphere查詢。 $ near和$ nearSphere是不同的。 maxDistance應該以米爲單位。 1000.fdiv(111.12)是什麼意思? – astroanu
從[這裏](http://stackoverflow.com/a/7702456/653378),'1000.fdiv(111.12)'應該將km轉換爲度(所以1000km度)。我編輯了我的問題,實際上是'$ near'工作,如果我直接在'Location'模型中查詢,所以我認爲它與mongoid ... – evuez
度或弧度有關?對不起,我不熟練使用ruby語法,但mongo不支持度數值,它必須是弧度。 $ nearSphere算法將距離計算爲球體,而$ near只會計算爲平面。對於地理定位計算,nearSphere會爲您提供準確的結果。 – astroanu