简体   繁体   中英

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...

I have a mongo database of records that contains records like this - with hashes embedded within hashes embedded within array

{
  "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?

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. Then simply search as usual on your Address object rather than your User object. Also you may consider indexing the street attribute on your Address object so that it becomes faster when searching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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