2012-04-04 72 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張貼它,以防萬一有人需要它:)