mongoid在一个哈希数组内的数组中搜索

Mun*_*sim 1 mongodb mongoid

Object embeds_many searched_items

这是文件:

{"_id": { "$oid" : "5320028b6d756e1981460000" },

"searched_items": [
{
  "_id": { "$oid" : "5320028b6d756e1981470000" },
   "hotel_id": 127,
  "room_info": [
    {
       "price": 10,
      "amenity_ids": [
        1,
        2
      ]
    },
    {
      "price": 160,
      "amenity_ids": null
    }
  ]
  },
  {
  "_id": { "$oid" : "5320028b6d756e1981480000" },
  "hotel_id": 161,
  "room_info": [
    {
      "price": 400,
      "amenity_ids": [4,5]
    }
   ]
  }
 ] 
}
Run Code Online (Sandbox Code Playgroud)

我想找到具有room_info.amenity_idsIN [2,3] 的"searching_items" .

我试过了

object.searched_items.where('room_info.amenity_ids' => [2, 3])

object.searched_items.where('room_info.amenity_ids' =>{'$in' => [2,3]}

没有运气

r3b*_*o0t 5

mongoid提供了elem_match方法,用于在Array Type的对象中进行搜索

例如

class A
  include Mongoid::Document
  field :some_field, type: Array
end

A.create(some_field: [{id: 'a', name: 'b'}, {id: 'c', name: 'd'}])

A.elem_match(some_field: { :id.in=> ["a", "c"] }) => will return the object
Run Code Online (Sandbox Code Playgroud)

如果您有任何其他疑问,请告诉我.

更新

class SearchedHotel
  include Mongoid::Document
  field :hotel_id, type: String
  field :room_info, type: Array
end

SearchedHotel.create(hotel_id: "1", room_info: [{id: 1, amenity_ids: [1,2], price: 600},{id: 2, amenity_ids: [1,2,3], price: 1000}])
SearchedHotel.create(hotel_id: "2", room_info: [{id: 3, amenity_ids: [1,2], price: 600}])

SearchedHotel.elem_match(room_info: {:amenity_ids.in => [1,2]})

Mongoid::Criteria
 selector: {"room_info"=>{"$elemMatch"=>{"amenity_ids"=>{"$in"=>[1, 2]}}}}
 options:  {}
 class:    SearchedHotel
 embedded: false
Run Code Online (Sandbox Code Playgroud)

它返回两个记录.我错过了你的问题/要求.如果是,请告诉我.