D_Asti
D_Asti

Reputation: 69

How to aggregate distinct items in mongo db to separate array?

I have an API endpoint that checks the mongo db and returns in a following structure for example:

{
  "Name": "Test"
  "Location": "Whatever",
  "customerServices": [
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "West",
        "name": "test"
      },
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "West",
        "name": "test"
      },
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "East",
        "name": "test"
      }
  ]
}

What I want to do is to add aggregation to the pipeline that would create additional field-serviceCounties and include distinct serviceCounty values from the customerServices array. Like the following:

{
  "Name": "Test"
  "Location": "Whatever",
  "customerServices": [
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "West",
        "name": "test"
      },
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "West",
        "name": "test"
      },
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "East",
        "name": "test"
      }
  ],
  "serviceCounties": [
    {
      "countyName":"East"
    },
    {
      "countyName":"West"
    }
] 
}

I have tried the following, but it didn't work. There something I'm missing or doing wrong:

                'serviceCounties': {
                    '$reduce': {
                        'input': '$services.event.services',
                        'initialValue': [],
                        'in': [{
                            "countyName": { '$concatArrays': ["$$value.serviceCounty", "$$this"] }
                        }]
                    }
                }

Any ideas how to do it ?

Upvotes: 0

Views: 68

Answers (1)

Pinky Promise
Pinky Promise

Reputation: 223

You could try this.

db.collection.aggregate([
  {
    $addFields: {
      "serviceCounties": [
        {
          $map: {
            input: "$customerServices",
            in: {
              "countyName": "$$this.serviceCounty"
            }
          }
        }
      ]
    }
  }
])

Playground

$addfields to add serviceCounties array
$map to get the customerServices values.

Upvotes: 1

Related Questions