Mongodb, how do I aggregate match / group some documents but only if one or other conditions are satisfied?

566 views Asked by At

I have two properties b and u that are arrays. I want my query to return me all documents that have at least 1 element in b that satisfies condition 1 or at least 1 element in u that satisfied condition 2.

My problem is that if condition 1 is satisfied, it will return me the array b with all elements that satisfy it, AND ALL the elements from u. Same with condition B.

I want: If there is an element in b that satisfied condition 1, return me that array with the elements that satisfy it. If not, empty array or exclude b. Same with condition 2 and u.

If no elements satisfy the conditions, exclude the document.

1

There are 1 answers

1
WiredPrairie On BEST ANSWER

Unfortunately, you can't do that with MongoDB in a single step on the database server. You'll need to do it client side.

While you can project (documentation) your results to only include/exclude some fields (or the first matching result in an array for example as shown here), you can't conditionally do it based on a search with multiple arrays (and the projection operator returns only the first match, not just the results that match).

You might need to consider a different document/collection structure to meet your requirements. MongoDB doesn't have sub-document level filtering/searching yet.