简体   繁体   中英

Mongoid querying for parent by embedded children (using two values)

I have a Contact model, that has embedded Email models

I am trying to query a Contact record, to find all the Contacts that have an Email address where the 'email_type' matches a string, and the 'unsubscribed' flag for that email is false

MY best hit so far is:

Contact.where({"emails.email_type" => 'Work','emails.unsubscribed'  => false})

But this finds Contacts where any email address if of type 'Work' OR any email address is unsubscribed - this means too many contacts are returned

What I need to do is find Contacts where any email address if of type 'Work' AND that email address is also unsubscribed ... is there a way to do this?

Turns out the syntax is pretty simple, if very hard to find ...

Contact.elem_match("emails" =>  { email_type: type, unsubscribed: false })

elem_match from http://mongoid.org/en/origin/docs/selection.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM