2011-10-09 83 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对象或坐标。