0

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?

  • 1
    Possible duplicate of [Mongoid / Mongodb and querying embedded documents](http://stackoverflow.com/questions/3954520/mongoid-mongodb-and-querying-embedded-documents) – Blakes Seven Mar 12 '16 at 00:10

2 Answers2

0

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
toddmetheny
  • 4,405
  • 1
  • 22
  • 39
  • 1
    Little too "rubyesque" to be the best way to use a "database". Besides, there is a [much simpler way](https://docs.mongodb.org/manual/core/document/#dot-notation) when using MongoDB, as is what the question is asking. – Blakes Seven Mar 12 '16 at 00:11
-1

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.