2015-12-09 129 views
0

我有兩個模型,LocationEventMongoid 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對象。

我在做什麼錯?

+0

我還沒有用過ruby,請參閱這裏瞭解如何製作一個使用mongo https://docs.mongodb.org/manual/reference/operator/query/nearSphere/的nearSphere查詢。 $ near和$ nearSphere是不同的。 maxDistance應該以米爲單位。 1000.fdiv(111.12)是什麼意思? – astroanu

+0

從[這裏](http://stackoverflow.com/a/7702456/653378),'1000.fdiv(111.12)'應該將km轉換爲度(所以1000km度)。我編輯了我的問題,實際上是'$ near'工作,如果我直接在'Location'模型中查詢,所以我認爲它與mongoid ... – evuez

+0

度或弧度有關?對不起,我不熟練使用ruby語法,但mongo不支持度數值,它必須是弧度。 $ nearSphere算法將距離計算爲球體,而$ near只會計算爲平面。對於地理定位計算,nearSphere會爲您提供準確的結果。 – astroanu

回答

0

這看起來像是一個急切的加載問題給我。你有沒有試過.includes(:location)

Event.includes(:location).where('location.coordinates' => {'$near' => [40.7127837, -74.0059413], '$maxDistance' => 1000.fdiv(111.12)}).first 

我之前mongoid工作,但似乎無法假如需要敲定,和哪個版本是。在某些版本的所有型號上默認啓用預加載,並且需要設置配置文件標識映射中的舊版本,但在版本4中這已不復存在。

+0

我使用Mongoid 5,我試過'includes'但仍然沒有結果。 – evuez