我是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”?
答案 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
属性建立索引,以便在搜索时变得更快。