简体   繁体   English

如何将 mongo db 中的不同项目聚合到单独的数组中?

[英]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:我有一个 API 端点,它检查 mongo db 并以以下结构返回,例如:

{
  "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.我想要做的是将聚合添加到管道中,这将创建额外的 field-serviceCounties并包含来自 customerServices 数组的不同serviceCounty 值。 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 $addfields添加serviceCounties数组
$map to get the customerServices values. $map以获取customerServices值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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