Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find embedded Mongoid documents based on multiple criteria?

I have a Mongoid document with embedded documents in it. I want to search the top-level documents for all of them where there is an embedded document that has multiple criteria.

TopDoc.where('inside.first_name' => 'Bob', 'inside.last_name' => 'Jones')

But it seems to me this would match on a TopDoc with Bob Wever and Paul Jones, which is wrong.

like image 331
Eric Avatar asked Jan 22 '26 20:01

Eric


1 Answers

You need to use $elemMatch. With Mongoid, the following line should do the trick

TopDoc.elem_match(inside: { first_name: 'Bob', last_name: 'Jones' })

which is equivalent to :

TopDoc.where(:inside.elem_match => { first_name: 'Bob', last_name: 'Jones'})
like image 169
Aymeric Avatar answered Jan 24 '26 18:01

Aymeric



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!