Home > Enterprise >  Replace empty result from group stage output in mongo aggregation
Replace empty result from group stage output in mongo aggregation

Time:11-09

I have a group stage in my pipeline like:

$group: {
  _id: null,
  count: {$sum: 1},
  results: {$push: '$$ROOT'}
}

Sometimes $$ROOT is empty and there are no results. In theses cases, I get an empty result after the group stage which is not my desired behaviour. I want to get the below object, instead with a zero count and empty results.

[
{
  count: 0,
  results: []
}
]

How can I achieve this? I tried to replace the root (by replaceRoot) but it seems when there is nothing there is no root either.

CodePudding user response:

Query

  • the normal way to do it i think its on the driver with simple code
  • but you can also do it on the database, with more complicated code
  • "empty_result" is a collection containing this
    [{"count": 0,"results": []}]

Example with data
Example without data

docs.aggregate(
[{"$group": 
   {"_id": null, "count": {"$sum": 1},
    "results": {"$push": "$$ROOT"}}},
 {"$unionWith": {"coll": "empty_result"}},
 {"$sort": {"count": -1}},
 {"$limit": 1}])
  • Related