2012-03-16 98 views
1

當前是否可以使用基於Mongoid的對象搜索BSON :: OrderedHashes數組?我的一個屬性,我們稱之爲foobar類,看起來像下面這樣:Mongoid:搜索數組

[#<BSON::OrderedHash:0x7f0 {"id"=>"4bf58dd8d48988d118951735", "name"=>"Grocery or Supermarket", "pluralName"=>"Grocery or Supermarkets", "shortName"=>"Grocery Store", "icon"=>#<BSON::OrderedHash:0x7f2 {"prefix"=>"https://foursquare.com/img/categories/shops/food_grocery_", "sizes"=>[32, 44, 64, 88, 256], "name"=>".png"}>, "primary"=>true}>] 

我想通過我的所有對象,並找到每一個包含雜貨店順序散列'name'屬性。

回答

6

我想你應該能夠做這樣的事情:

Bar.where('foo.name' => /Grocery/) 

MongoDB的multikeys support將通過數組元素搜索的關懷和'foo.name'將尋找namefoo

+0

這太棒了。謝謝! – randombits 2012-03-16 20:45:11

+1

@randombits:另外,如果你可以在開頭定位你的正則表達式(例如'/ Grocery /'),那麼你可以索引'foo.name',並且MongoDB將使用索引來進行正則表達式搜索。 – 2012-03-16 20:56:01

0

沒有測試過這個,但我認爲像這樣的東西可能會起作用。

Bar.all.select {|b| b.foo.select{|f| f['name'] == 'Grocery'}.size > 0}