Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$in requires an array as a second argument [duplicate]

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!

like image 936
Alexandru Comanescu Avatar asked Feb 04 '19 00:02

Alexandru Comanescu


1 Answers

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'
    }
}
like image 193
Saravana Avatar answered Dec 30 '22 05:12

Saravana