mongodbaggregation-framework

Aggregation on $group and $count query should skip the null values while returning 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.

aggregation stage


Solution

  • You can keep your current pipeline. Just add a $unionWith stage at the end to append a count: 0 document. Then, perform a $limit: 1 to pick the 1st document. If there is non-null result, it will be picked up as the first document and return the count result. If there is only null result, it will pick up the count: 0 document we appended.

    db.collection.aggregate([
      {
        $group: {
          _id: "$party1.partyRole"
        }
      },
      {
        "$match": {
          _id: {
            $ne: null
          }
        }
      },
      {
        "$count": "count"
      },
      {
        "$unionWith": {
          "coll": "collection",
          "pipeline": [
            {
              "$documents": [
                {
                  "count": 0
                }
              ]
            }
          ]
        }
      },
      {
        "$limit": 1
      }
    ])
    

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