2011-10-09 86 views

回答

47

可以在mongoid

class Item 
    include Mongoid::Document 

    field :loc, :type => Array 

    index(
     [ 
      [:loc, Mongo::GEO2D]    
     ], background: true 

) 
end 

而對於查詢

$附近命令(不maxDistance)

location = [80.24958300000003, 13.060422] 
items = Item.where(:loc => {"$near" => location}) 

$附近命令定義地理指標如下(以maxDistance)

由111.
distance = 10 #km 
location = [80.24958300000003, 13.060422] 
items = Item.where(:loc => {"$near" => location , '$maxDistance' => distance.fdiv(111.12)}) 

轉換距離(一個度約爲111.12公里)的使用公里時,或離開距離,因爲它是使用度

$ centerSphere/$ nearSphere查詢

location = [80.24958300000003, 13.060422] 
items = Item.where(:loc => {"$within" => {"$centerSphere" => [location, (distance.fdiv(6371))]}}) 

這將在10公里範圍內找到物品。在這裏,我們需要將距離/ 6371(地球半徑)轉換爲與km一起工作。

$箱(邊框查詢)

first_loc = [80.24958300000003, 13.060422] 
second_loc = [81.24958300000003, 12.060422] 
items = Item.where(:loc => {"$within" => {"$box" => [first_loc, second_loc]}}) 

這將幫助你找到給定的邊框內的項目。

+0

當我嘗試使用$附近命令(maxDistance)它返回一個錯誤: 地理值必須是數字:{$ maxDistance:0.001799856011519079,$附近:80.249,13.060422]} 有什麼想法?它適用於「$ near」,但是當我添加「$ maxDistance」時,它會窒息。 – Vasily

+0

@Vasily,我不確定.. $ maxdistance的$ near查詢完全符合您指定的值。 'Item.where(:loc => {「$ near」=> [80.249,13.060422],'$ maxDistance'=> 0.001799856011519079})'。它工作正常..也許你可以告訴我你正在嘗試的查詢?我們將會看到 – RameshVel

+0

我使用maxDistance時出現同樣的錯誤。 Ruby 1.8。你們有沒有找到解決辦法? –

7

RameshVel的回答很好。

爲更新,在Mongoid 3.0.4,我有如下,以使其與rake db:mongoid:create_indexes工作來定義索引:

index(
    { loc: Mongo::GEO2D }, 
    { background: true } 
) 
+6

其實這對於''Mongoid 3.0.0'不適合我,這個文檔指出'index({loc:「2d」},{min:-200,max:200})'格式。乾杯。 – rjgonzo

0

所有這些問題的答案是過時與MongoDB中的最新版本,並會拋出一些uninitialized constant Mongo::GEO2D

對於mongoid 4/5,我建議你看看mongoid-geospatial gem如果你需要玩2D對象或座標。