0

With given data

{
    "type": "INGESTION",
    "message": "Lorem"
}

{
    "type": "INGESTION",
    "message": "Ipsum"
}

{
    "type": "DISCHARGE",
    "message": "dolor"
}

{
    "type": "DISCHARGE",
    "message": "sit"
}

I want to group by type and collecting all possible values of message into one single field.

The expected output should be something along the lines of

[{
    "type": "INGESTION",
    "messages": ["Lorem", "Ipsum"]
},
{
    "type": "DISCHARGE",
    "messages": ["dolor", "sit"]
}]

I have tried several aggregation queries, none of which have led to a result that I could be satisfied with.

manuelgu
  • 105
  • 10

1 Answers1

1

There is an example on the doc which describes your same situation.

db.your_collection.aggregate([
    {
        $group: {
            "_id": "$type",
            "messages": { $push: "$message" }
        }
    }
]);
Marco Luzzara
  • 5,540
  • 3
  • 16
  • 42