I have a document with an array field named items
. This is an optional field and not always set within the document. So this could either be undefined, empty array, or contain an array of id numbers [1, 2, 3]
.
What I’m trying to do is return all documents if the items
array does not exist or is empty, otherwise it should only return those that match a provided id
. For example:
//This would not match (no documents) returned
id = 4
items = [1,2,3]
//This would match
id = 4
items = []
or
items = [1,2,3,4]
or
items is undefined (does not exist)
This is being done in a pipeline aggregation and tried using $expr
with $cond
but just not getting there…
Any help would be greatly appreciated. Thank you!
3
Answers
This is the solution I ended up going with:
MONGO PLAYGROUND
You can use
$ifNull
to wrap the undefined case and empty array case into []. Then use$in
to handle the case where the array contains 4. Use$or
to chain up the 2 criteria.Mongo Playground