Anyway for $lookup to return either a null or empty array?

Curious if I can use $lookup to find where there are no matches ?

I am not sure I understand but if you do $lookup and nothing is found in the looked up collection the array will be empty.

And, if you are only interested on source document for which the $lookup produce an empty array you may add the stage:

{ "$match" : { "lookup_as_field_name.0" : { "$exists" : false } } }

Exactly what I was looking for. I had been trying it with $size: 0 (in a match stage) which didn’t work but this does. Thank you!

1 Like

Something I forgot to mentioned.

Since you are only interested in the no match case, it might be a good idea to prevent the $lookup stage to build an array with more than an element. That is make the $lookup to stop at the first match if multiple match is possible.

Not entirely following you. I’d want all matches though not just the first.

I am the one not following now. By

I understood that you wanted to process the documents without matches. If you want both the one with matches and the one without matches, then you have nothing special to do. You will get an empty array when there is not match and a populated array with the matches when it matches.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.