1

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.

Web Jigooli
  • 49
  • 1
  • 6
  • You can check the aggregation output (which is a cursor of documents), and see if it is empty. For example, `var cur = db.collection.aggregat([ ... ]); var arr = cur.toArray(); if (arr.length === 0) { printjson( { count: 0, results: [] } ) };` – prasad_ Nov 08 '21 at 11:43
  • @prasad_ Is there a way to handle it inside pipeline by adding some stages? – Web Jigooli Nov 08 '21 at 13:13

1 Answers1

1

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": []}]

PlayMongo

docs.aggregate(
[{"$group": 
   {"_id": null, "count": {"$sum": 1},
    "results": {"$push": "$$ROOT"}}},
 {"$unionWith": {"coll": "empty_result"}},
 {"$sort": {"count": -1}},
 {"$limit": 1}])
Takis
  • 8,314
  • 2
  • 14
  • 25
  • Thanks! It seems that unionWith is not supported by mongoose. Any workaround for this? – Web Jigooli Nov 08 '21 at 15:18
  • hmm, mongoose allows to write MQL as json in aggregations so i think it wont be mongoose problem(not sure thow), maybe you have old version of mongodb? union is kinda new requires MongodDB 4.4. – Takis Nov 08 '21 at 15:23
  • @_Takis I'm actually using mongo 4.4.1. with mongoose 6.0.12 and I get "TypeError: query.unionWith is not a function" – Web Jigooli Nov 08 '21 at 15:33
  • i think you are probably using the mongoose query builder(and union isnt added yet), mongoose allows us to use JSON raw, like [this](https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate) first example is raw JSON, the second is with the query builder.But this can be fixed using [this](https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-append) keep the query builder, and append the union stage with raw JSON. I dont use mongoose but i think you will be ok – Takis Nov 08 '21 at 15:43