Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why elem_match is returning 0 elements?

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?

like image 807
Fran Martinez Avatar asked May 19 '26 10:05

Fran Martinez


1 Answers

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
like image 173
Maxim Pontyushenko Avatar answered May 21 '26 01:05

Maxim Pontyushenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!