如何通过哈希值在散列内的哈希数组中进行搜索?

时间:2016-03-11 23:15:25

标签: ruby-on-rails ruby mongodb hash

我是ruby和Mongo的新手,我正在寻找答案......

我有一个mongo记录数据库,其中包含这样的记录 - 哈希嵌入在数组中嵌入的哈希

{
  "id =>1",
  "address" =>[
    {
      "number" => 1404,
      "street" =>"jasmine",
      "city" => "NY",
      "state" => "NY",
      "zip" => "02941"
    }, 
    {
      "number" => 2400,
      "street" =>"miner",
      "city" => "Boston",
      "state" => "MA",
      "zip" => "02760"
    },
    {etc..}
  ], 
  "geo" => { "lat" => 33.875, "lon" => -116.301 }     
  "first_name"=> "joe",
  "last_name" =>  "smith"
}

{ 
  "id" =>"2",
  "address" =>[{...},{...}, etc ],
  "geo" => {"lat" => 32.875, "lon" => -115.301 }, 
  "first_name"=> "john",
  "last_name"=>"doe"
} 

我希望找到/返回包含“street”==“jasmine”的所有记录,如何在查找条件中引用“street”?

2 个答案:

答案 0 :(得分:0)

如果你循环遍历每个对象:

objects_on_jasmine_street = []

NameOfObject.find_each do |object|
  if object['address'][0]['street'] # this will return street
     object_on_jasmine_street << object
  end
end

objects_on_jasmine_street

答案 1 :(得分:-1)

我相信在Mongo中搜索数组属性非常慢 - 考虑将地址的哈希值转换为对象实例。然后,只需在Address对象而不是User对象上进行搜索。您也可以考虑为street对象上的Address属性建立索引,以便在搜索时变得更快。