Can i get result of different query in one aggregation?

I’ve a collection like this:

I want to group them by name, and i want get the size of the document for both status pending and done . I able to get only pending one using { match: {status: "pending"}} .

I want to get the result like this:

  id: "Ali",
  pendingOrder: 11,  //status = "pending"
  doneOrder: 10,    // status = "done"
  pendingOrder: 12,
  doneOrder: 20

Is it possible to do that in one aggregation?

Look at $group.

First do not $match, or


Your first $group would look like:

$group : {
  _id : { name : "$Name" , "status" , "$Status" } 
  count : { "$sum" : 1 }

Then a second $group like

$group : {
  _id : "$_id.Name" ,
  counts : { $push : { "Status" : "_$id.Status" , count : "$count" } }

The result will not be in the exact format you wish but close enough. May be $arrayToObject can do the final transformation. But I prefer to do this data cosmetic in the application rather than the data server.

1 Like

Hi @elss

Other than @steevej suggestion, you also might want to have a look at $facet to see if it satisfies your requirements. However I would suggest that you use the method that you’re more comfortable with and can maintain easily.

Best regards