Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter out null array elements from a group value in a mongo aggregate query?

My aggregate $group is:

{
    $group: {
        _id: { ["$dayOfYear"]: "$TagDateCreated" },
        disqualified: {
            $addToSet: {
                $cond: {
                    if: { $in: [ "$TagId", [109,220,115,113,238] ]},
                    then: "$ContactId",
                    else: null
                }
            }
        }
    }
}

Which gives me a unique set of contactId's as disqualified but I need the null values removed. I've tried omitting the else statement int he $cond and various $filters in the $project that either don't remove anything, remove everything, or error.

like image 988
Bradley Avatar asked Sep 06 '18 17:09

Bradley


1 Answers

You can add next pipeline stage after $group:

{
    $addFields: {
        disqualified: {
            $filter: {
                input: "$disqualified",
                as: "d",
                cond: {
                    $ne: [ "$$d", null ]
                }
            }
        }
    }
}

$addFields will overwrite existing array and using $filter you can remove null value

like image 173
mickl Avatar answered Oct 15 '22 14:10

mickl