简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM