Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

$count does not return 0 when no documents found

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  data: []
}

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

{
  data: [],
  total: 0
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading