2012-04-04 30 views
4

我想在MongoMapper支持的模型中封装一个近距离查询与maxDistance。MongoMapper与maxDistance附近 - Mongo :: OperationFailure:地理值必须是数字:

我在查询语法中必须做些傻事。

型号

class Site 
    include MongoMapper::Document 

    key :id, Integer 
    key :name, String 
    key :location, Array 
    ensure_index [[:location, '2d']] 


    def self.nearest(center_point, range) 
    where(:location => {'$near' => center_point, '$maxDistance' => range}).all 
    end 

end 

试图获得200英里范围内一个点的一切......

Site.nearest([ - 122.0,44.0] 200)

> Mongo::OperationFailure: geo values have to be numbers: { 
> $maxDistance: 200, $near: [ -122.0, 44.0 ] } from 
> /Library/Ruby/Gems/1.8/gems/mongo-1.6.1/lib/mongo/cursor.rb:144:in 
> `next' from 
> /Library/Ruby/Gems/1.8/gems/mongo-1.6.1/lib/mongo/cursor.rb:290:in 
> `each' from 
> /Library/Ruby/Gems/1.8/gems/mongo-1.6.1/lib/mongo/cursor.rb:308:in 
> `to_a' from 
> /Library/Ruby/Gems/1.8/gems/mongo-1.6.1/lib/mongo/cursor.rb:308:in 
> `to_a' from 
> /Library/Ruby/Gems/1.8/gems/plucky-0.4.4/lib/plucky/query.rb:74:in 
> `all'  from /Users/nick/Code/web/map/app/models/site.rb:40:in 
> `nearest'  from (irb): 

回答

1

我猜这实际上是一个数据问题或索引问题,你的查询看起来是正确的。

参见http://www.mongodb.org/display/DOCS/Geospatial+Indexing ... 200 MaxDistance可能太大:

缺省情况下,索引假设你索引经度/纬度,并且因此配置为[-180..180)值范围。

距离单位与坐标系中的距离单位相同。

也试试Site.distinct(:location)并查找任何非数字数据。 (或者如果你不在MM 0.11.1上,则为Site.query.distinct(:location))。

提示:如果你想看到什么查询去看看,当它击中的MongoDB一样,添加.criteria.to_hash

Site.where(:location => {'$near' => center_point, '$maxDistance' => range}).criteria.to_hash 
# => 
{ 
    :location=> { 
    "$near"  => [-122.0, 44.0], 
    "$maxDistance" => 200 
    } 
} 
12

你可能遇到了this bug需要$near$maxDistance$maxDistance订购第一。

在任何情况下,我发现这个问题,因为我使用PyMongo时得到了OperationFailure: database error: geo values have to be number,并且交换订单修复了它。

+0

此修复程序也适用于我。谢谢你为我节省了一些时间。 – Alice 2013-07-23 15:53:03

1

这里的另一种解决方案for this one

{'location' : SON([('$near', [55.55632, 25.13522]), ('$maxDistance', 0.01)])}) 
0

得到这个错误与存储在会话DATAS(不同的比赛,PHP + ZF2):一个floatval(LAT),floatval(LON)解决了这个问题:) 我m张贴它,以防万一有人需要它:)