I'm trying to make some aggregations and I have the following problem. I need to use "pipeline" and I'm getting an error when the array I'm looking for is missing.
{
$lookup: {
from: 'comments',
let: { comments: '$comments' },
pipeline: [
{
$match: {
$expr: {
$in: ['$_id', '$$comments']
},
isDeleted: false
}
}
],
as: 'comments'
}
}
With this stage I get the following error:
'$in requires an array as a second argument, found: missing'
Because not all documents have the field "comments".
Note: I'm using pipeline instead of foreingField and localField because I need to filter with isDeleted: false
and maybe other matching conditions.
Is there anyway to make this lookup only if the document has the field comments?
Thank you!
you can add $ifNull
or $and
with not null or exists condition in $expr
{
$lookup: {
from: 'comments',
let: { comments: '$comments' },
pipeline: [
{
$match: {
$expr: {$and: [
{$in: ['$_id', {$ifNull :['$$comments',[]]}]},
{$eq: ["$isDeleted", false]}
]}
}
}
],
as: 'comments'
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With