如何使用 MongoDB 聚合将多个字符串字段连接成单个字段?

时间:2021-02-08 10:03:39

标签: python mongodb aggregation-framework pymongo

假设我有以下格式的传入数据:

{
  "Name": "Test"
  "Location": "Whatever",
  "customerServices": [
      {
        "id": "test",
        "cusId": "test",
        "adr": "Adr 1",
        "serviceCounty": "Center",
        "area": "village"
      },
      {
        "id": "test",
        "cusId": "test",
        "adr": "adr2",
        "serviceCounty": "West",
        "area": "city"
      },
      {
        "id": "test",
        "cusId": "test",
        "adr": "test",
        "serviceCounty": "West",
        "area": "test"
      }
  ]
}

任何想法,如何编写聚合查询:

  1. 创建一个名为“serviceAreas”的新字段。类型:列表
  2. 对于“customerServices”中的每个项目。它将选择:adrserviceCountyarea 字段。
  3. 将它们一起附加到一个字符串中,然后添加到新创建的 serviceAreas 字段中。
  4. 它只会为不同的 serviceCounty 项目选择和执行操作

所以最终结果是这样的:

{
  "Name": "Test"
  "Location": "Whatever",
  "customerServices": [
      {
        "id": "test",
        "cusId": "test",
        "adr": "Adr 1",
        "serviceCounty": "Center",
        "area": "village"
      },
      {
        "id": "test",
        "cusId": "test",
        "adr": "adr2",
        "serviceCounty": "West",
        "area": "city"
      },
      {
        "id": "test",
        "cusId": "test",
        "adr": "test",
        "serviceCounty": "West",
        "area": "test"
      }
  ],
  "serviceAreas": [
       "Adr 1, Center, village", "adr2, West, city"
]
}

感谢任何帮助!

这是我尝试过的,但没有成功:

'serviceAreas': {
    '$reduce': {
        'input': '$serviceImpactHistory.event.services',
        'initialValue': [],
        'in': {
            '$setUnion': [
                '$$value', {'$concat': ['$$this.serviceCounty', '$$this.adr', '$$this.area']}
            ]
        }
    }
},

1 个答案:

答案 0 :(得分:1)

您不需要使用 $setUnion,只需使用 $concat 创建您的字符串

db.collection.aggregate([
  {
    $addFields: {
      serviceAreas: {
        "$reduce": {
          "input": "$customerServices",
          "initialValue": "",
          "in": {
            "$concat": [
              "$$value",
              "$$this.serviceCounty",
              ", ",
              "$$this.adr",
              ", ",
              "$$this.area",
              ", "
            ]
          }
        }
      }
    }
  }
])

Try it here