Why does elem_match return 0 items?

I'm trying to get one write result from a collection of objects, but after doing Mongoid documentation, I don't know what else to try.

I have this single element:

 > 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", ...>

      

this list of matches:

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

      

And this code is trying to get elements that match:

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

      

Why is it returning an empty array, is there one that matches?

+3


source to share


3 answers


According to mongodb official guide

The $ elemMatch operator matches documents containing an array field

And you are trying to use it with a hash field so that you basically misunderstand this choice. So there is no object that matches.



Instead, you should do:

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

      

+2


source


I cannot solve this problem with the method match_elem

, so I decided to do it via and

. I'm not very happy with this solution, and I still don't understand why it match_elem

doesn't return records, but at least I found a solution to unblock this feature.



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

      

+1


source


You don't need here elemMatch

. It's for finding the elements of an array of objects by partial matches (where you don't need full equality of the object, but only one or more fields)

This should work for your case.

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

      

+1


source







All Articles