我有一个mongodb集合。使用ruby驱动程序,以下工作:
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 ruby驱动程序。
感谢所有的帮助,谢谢。
答案 0 :(得分: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
ruby 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