MongoDB groupby - pull comma separated values in a field

Viewed 272

I want to groupby the collection and want to pull the comma-separated values.

In the below example, I want to group by "type" and want to pull $sum of "total" and all possible unique values of "value" in a field that should be comma seperated.

collection:

[
    {
        "type": "1",
        "value": "value1",
        "total": 10
    },
    {
        "type": "1",
        "value": "value3",
        "total": 20
    },
    {
        "type": "1",
        "value": "value3",
        "total": 30
    },
    {
        "type": "2",
        "value": "value1",
        "total": 10
    },
    {
        "type": "2",
        "value": "value2",
        "total": 20
    }
]

The output that I am expecting:

[
    {
        "type": "1",
        "value": "value1,value3",
        "total": 60
    },
    {
        "type": "2",
        "value": "value1,value2",
        "total": 30
    }
]

Please help to provide the approach or code.

1 Answers

This can be achieved just with $group and $project aggregation methods:

https://mongoplayground.net/p/230nt_AMFIm

db.collection.aggregate([
  {
    $group: {
      _id: "$type",
      value: {
        $addToSet: "$value"
      },
      total: {
        $sum: "$total"
      }
    },
    
  },
  {
    $project: {
      _id: 0,
      type: "$_id",
      value: "$value",
      total: "$total"
    }
  },
])
Related