简体   繁体   English

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

[英]How do I search within an array of hashes inside a hash by hash values?

I am new to ruby and Mongo and am looking for an answer to this... 我是红宝石和Mongo的新手,正在寻找答案...

I have a mongo database of records that contains records like this - with hashes embedded within hashes embedded within array 我有一个包含这样的记录的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"
} 

and I want to find/return all records that include "street" == "jasmine", how do I reference "street" inside the find criteria? 并且我想查找/返回所有包含“ street” ==“ jasmine”的记录,如何在查找条件中引用“ street”?

if you're looping through each object: 如果要遍历每个对象:

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

I believe searching array attributes in Mongo is pretty slow - consider converting your hashes for addresses into object instances. 我认为在Mongo中搜索数组属性相当缓慢-考虑将地址的哈希转换为对象实例。 Then simply search as usual on your Address object rather than your User object. 然后,只需像往常一样在您的Address对象而不是User对象上进行搜索。 Also you may consider indexing the street attribute on your Address object so that it becomes faster when searching. 您也可以考虑在Address对象上索引street属性,以便在搜索时变得更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM