I want to query for documents that have a subdocument that contains two values.
I have a main document, Account, that contains none or more sales subdocuments. Each sale has a sale_price and sale_date. I only want accounts that have a sale subdocument with a sale_price greater than 0 and sale_date in the last 4 years.
Here is what I’ve tried;
Account.and("sales.sale_date" => {"$gt" => Date.today - 4.years}, "sales.sale_price" => {"$gt" => 0})
This returns accounts that have “any” sales in the last 4 years and have “any” sale with a sale_price > 0. I want only Accounts have a sale with both criteria true on the same document.
Any advice?
As happens so often, more investigation after asking a question turns up a solution. The elem_match method appears to do what I need.
Here’s what I came up with;