Grouping results after $facet

Hi there,

Suppose my $facet stage returns something like this:

{
  "messagesArray": [
  {
    "_id": 1,
    "messages": []
  },
  {
    "id": 2,
    "messages": ["Message1", "Message2"]
  },
  {
    "_id": 3,
    "messages": ["Message3"]
  }
  ],
  "objectsBought": [
  {
    "_id": 1,
    "bought": 10
  },
  {
    "_id": 2,
    "bought": 20
  }
  ],
  "objectsSold": [
  {
    "_id": 1,
    "sold": 20
  },
  {
    "_id": 3,
    "sold": 40
  }
  ]
}

What is the next stage to transform it into this ?

{[
{
  "_id":1,
  "messages":[],
  "bought": 10,
  "sold": 20
},
{
  "_id":2,
  "messages":["Message1", "Message2"],
  "bought": 20
},
{
  "_id":3,
  "messages":["Message3"],
  "sold": 40
}
]}

Any help or pointers highly appreciated :slight_smile:

The simplest and probably the less efficient way is to $unwind the three arrays, extract the _id and then $group this _id.

The more complicated way would be with $map and $mergeObjects.

A third way is to leave it alone and to the final grouping in the application.

@Robert_Zefield, some follow up would be appreciated.