为什么elem_match返回0个元素?

时间:2015-07-20 12:32:53

标签: ruby-on-rails mongoid

我试图从一组对象中获取一个记录结果,但在遵循Mongoid文档之后我不知道还有什么要尝试。

我有这个单一元素:

 > contacts
 => #<Contact _id: 55ace6bc6xx, device_fields: {"app_id"=>"55ace6bc65195efc8200xxxx"}, created_at: 2015-07-20 12:17:00 
    UTC, updated_at: 2015-07-20 12:17:00 UTC, name_first: "Kory", 
    name_last: "Funk", ...>

这个匹配者列表:

> apps = []
> apps << App.where(id: "55ace6bc65195efc8200xxxx").first.id
=> ["55ace6bc65195efc8200xxxx"] 

此代码尝试获取匹配的元素:

> contacts.elem_match(device_fields: {:app_id.in => apps }).to_a
=> []
> contacts.elem_match(device_fields: { "app_id": "55ace6bc65195efc8200xxxx"}).to_a
=> []

为什么它返回一个空数组呢?有一个匹配的数据?

3 个答案:

答案 0 :(得分:2)

根据官方mongodb manual

  

$ elemMatch运算符匹配包含数组字段

的文档

并且您正在尝试将其与哈希字段一起使用,因此您基本上误解了此选择。所以没有匹配的对象。

而不是你应该这样做:

contacts.where(:'device_fields.app_id'.in => apps).to_a

答案 1 :(得分:1)

我无法通过match_elem方法解决这个问题,所以最后我决定通过and来解决这个问题。我对这个解决方案不是很满意,但我仍然不明白为什么match_elem没有返回记录,但至少我找到了解锁此功能的解决方案。

contacts.and(:device_fields.exists => true,
             :device_fields.nin => ['', nil], 
             :"device_fields.app_id".in => apps).to_a

答案 2 :(得分:1)

你在这里不需要elemMatch。通过部分匹配(不需要完全对象,但只需要一个或多个字段)来查找对象数组元素

这适用于您的情况。

contacts.where('device_fields.app_id' => {'$in' => apps})