Home > Blockchain >  $count does not return 0 when no documents found
$count does not return 0 when no documents found

Time:10-20

I have the following aggregation pipeline in mongoDB:

[
  {
    "$match": {}
  },
  {
    "$facet": {
      "total": [
        {
          "$count": "rows"
        }
      ],
      "data": [
        {
          "$skip": 0
        },
        {
          "$limit": 200
        }
      ]
    }
  },
  {
    "$project": {
      "total": {
        "$first": "$total.rows"
      },
      "data": 1
    }
  }
]

The aggregation works fine if there are matches: for example: aggregation result (in case there are 2 documents in my collection)

{
  data: [{firstName: "Bob"}, {firstName: "Marry"}],
  total: 2
}

But it's not working good when there are NO matches: This is what the aggregation returns (in case there are 0 documents in my collection)

{
  data: []
}

I don't get why in case there is not matches, the total is not returned with 0, like this:

{
  data: [],
  total: 0
}

CodePudding user response:

This is how the aggregation framework operates in general.

If you'd like to always have a number there, then you could include a $ifNull check for total:

      "total": {
        "$ifNull": [
          {
            "$first": "$total.rows"
          },
          0,
          {
            "$first": "$total.rows"
          }
        ]
      }

Playground demonstration here

For what it's worth, you also don't need the $match at the beginning if no filter is being provided to it.

  • Related