I find a lot of questions about how to find a document based on some subdocument criterion, but is it possible to retrieve the subdocuments themselves, not the document in which they are contained?
Note - the proposed duplicate is not a duplicate. That OP asks how to return documents in a collection, each with a subset of matching subdocuments. My question is, how to retrieve only subdocuments that match.
From a collection like this:
{ name:"a" subs: [ { subname:"aa", value: 1 }, { subname:"ab", value: 2 } ] }
{ name:"b" subs: [ { subname:"ba", value: 2 }, { subname:"bb", value: 3 } ] }
I'd like to do a query that produces, just subdocs matching a query, say, where value === 2
.
I tried this:
myCollection.find().elemMatch("subs", { value:2 })
And that's close, but it just finds (in the example data), both upper-level documents, since their sub elements match. I know I could pick out the subdocuments from the result, but I'd like the query to do the work, and produce this...
{ subname:"ab", value: 2 }
{ subname:"ba", value: 2 }
... i.e. just the subdocs that match. Is it possible? Thanks in advance.