Stephen Romero
Stephen Romero

Reputation: 3032

MongoDB: How to default $count to 0 in a $facet when there is no matching criteria in aggregate

I am working on a complex pagination aggregate query and I am trying to see what Mongo is and isn't capable of doing. I followed this question here, and all works well except for when there is no data returned.

Mongo returns: { metadata: [], data: [] }, but I want to see if it's possible to return

{ metadata: [ { count: 0 } ], data: [] }

for the Front-End to handle easier. So far I haven't been able to achieve this.

Here's a snippet of the $facet pipeline I'm using :

{
  "$facet": {
    "metadata": [{
      "$count": "total"
    }],
    "data": [{
      "$skip": 0
    }, {
      "$limit": 10
    }]
  }
}

Of course this can be done after the query on the back-end, but I'm really wanting Mongo to handle it.

Upvotes: 1

Views: 1468

Answers (1)

turivishal
turivishal

Reputation: 36134

You can check condition at the end,

  • $addFields to check $cond if metadata array size is zero then return static array with total count zero otherwise return original metadata array
  // <= skipping your pipelines
  {
    $addFields: {
      metadata: {
        $cond: [
          { $eq: ["$metadata", []] },
          [{ total: 0 }],
          "$metadata"
        ]
      }
    }
  }

Playground


Other option with $switch case operator,

  • $switch to check first case if metadata is equal to [] then return total with zero and in default return original metadata array
  {
    $addFields: {
      metadata: {
        $switch: {
          branches: [
            {
              case: { $eq: ["$metadata", []] },
              then: [{ total: 0 }]
            }
          ],
          default: "$metadata"
        }
      }
    }
  }

Playground

Upvotes: 2

Related Questions