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

StackOverflow https://stackoverflow.com/questions/18429393

  •  26-06-2022
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top