2014-02-21 61 views
0

我有一個mongodb集合。使用Ruby驅動程序,以下工作:使用mongdb,ruby和sinatra如何使用數學和聚合函數?

search = 'LONDON' 
result = posts.find(:district => search).to_a.to_json 

併產生Firebug控制檯執行以下操作:

[{"_id":"{AB46B6E4-46F7-44F6-8D88-0002C05947BB}","price":"450000","date_sold":"2013-10-23 00:00","post_code":"NW6 2DT","house_type":"F","condition":"N","freehold":"L","house_number":"72","flat_number":"FLAT 3","street":"LOVERIDGE ROAD","town":null,"district":"LONDON","region":"CAMDEN","county":"GREATER LONDON"}] 

有30個記錄的集合中,當我改變了集合函數如下:

result = posts.find({ :price => { $gt => 100000 } }).to_a.to_json 

我在控制檯中得到一個空的[]。這是因爲集合中的數據類型沒有設置爲整數?如果是這樣,我如何以編程方式更改它(即不在shell中)?

或者是查詢錯誤?我正在使用mongodb紅寶石驅動程序。

謝謝各位的幫忙,謝謝。

回答

0

你太親近了 - 你的例子需要引用$ gt, ,價格字段的值需要是整數,而不是字符串,以便$ gt按你的意願工作。 這是一個驗證這一點的測試。希望這有助於。

test.rb

require 'mongo' 
require 'json' 
require 'test/unit' 

class MyTest < Test::Unit::TestCase 
    def setup 
    @posts = Mongo::MongoClient.new['test']['posts'] 
    @docs = JSON.parse <<-EOT 
[{"_id":"{AB46B6E4-46F7-44F6-8D88-0002C05947BB}","price":"450000","date_sold":"2013-10-23 00:00","post_code":"NW6 2DT","house_type":"F","condition":"N","freehold":"L","house_number":"72","flat_number":"FLAT 3","street":"LOVERIDGE ROAD","town":null,"district":"LONDON","region":"CAMDEN","county":"GREATER LONDON"}] 
    EOT 
    @posts.remove 
    @posts.insert(@docs) 
    end 

    test "find examples" do 
    result = @posts.find({ :price => { '$gt' => 100000 } }).to_a 
    assert(result.count == 0) 
    puts "result from post: #{result.to_json}" 

    @docs.each{|doc| doc.delete("_id"); doc["price"] = doc["price"].to_i} 
    @posts.insert(@docs) 
    result = @posts.find({ :price => { '$gt' => 100000 } }).to_a 
    assert(result.count > 0) 
    puts "result after fixes: #{result.to_json}" 
    end 
end 

紅寶石test.rb

Loaded suite test 
Started 
result from post: [] 
result after fixes: [{"_id":{"$oid": "5355e4c3a3f57661f3000001"},"price":450000,"date_sold":"2013-10-23 00:00","post_code":"NW6 2DT","house_type":"F","condition":"N","freehold":"L","house_number":"72","flat_number":"FLAT 3","street":"LOVERIDGE ROAD","town":null,"district":"LONDON","region":"CAMDEN","county":"GREATER LONDON"}] 
. 

Finished in 0.00482 seconds. 

1 tests, 2 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 
100% passed 

207.47 tests/s, 414.94 assertions/s 
+0

什麼明星,謝謝我真的很感激! – user1903663

+0

不客氣,我希望您的應用程序能夠提前放大。 –