Bradley
Bradley

Reputation: 2141

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.

Upvotes: 7

Views: 8669

Answers (1)

mickl
mickl

Reputation: 49945

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

Upvotes: 12

Related Questions