Aggregation on $group and $count query should skip the null value count

For the below query, the first aggregation will result null value and then it is counted as 1 in second stage, how can we skip counting the null value from the distinct
db.party.aggregate([
{ $group: { _id: “$party1.partyRole” } },
{ $count: “count” }
]);

stage1:
{ _id: “$party1.partyRole” } => _id: null

stage2:
“count” => 1

But from the stage one, if there is only null value then the count should skip it and show as 0 instead of 1.

Share your document.

If you get null with

the because your document has none.

@harish_j1, please followup on your thread.

The duplicate question on StackOverflow has an answer provided (by another user), which solves for null and non-null entries. (Has been marked as accepted there.)

Mongo Playground with only null result
Mongo Playground with non-null result

1 Like