I am trying to get one record result from a collection of objects, but after following the Mongoid documentation I don't know what more 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 matchers:
> apps = []
> apps << App.where(id: "55ace6bc65195efc8200xxxx").first.id
=> ["55ace6bc65195efc8200xxxx"]
And this code trying to get the 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 it there is one that matches?
According to official mongodb manual
The $elemMatch operator matches documents that contain an array field
And you are trying to use it with the hash field so you basically misunderstood this selection. So there is no object that matches.
Instead of it you should do:
contacts.where(:'device_fields.app_id'.in => apps).to_a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With