【问题标题】:How to concatenate multiple string fields into single field using MongoDB Aggregation?如何使用 MongoDB 聚合将多个字符串字段连接成单个字段?
【发布时间】:2021-02-08 10:03:39
【问题描述】:

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

{
  "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. 对于“客户服务”中的每个项目。它将选择: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']}
            ]
        }
    }
},

【问题讨论】:

  • 您可以尝试使用$reduce 运算符。
  • 是的,我明白了。但是,我有点无法理解整个事情。尝试将它与 $setUnion 和 $cascanate 一起使用,但它似乎不起作用。或者我做错了什么
  • 尝试在网上搜索$reduce的用法。另外,请包含您尝试过的代码,以便有人可以尝试帮助和解决问题。
  • 更新了,我已经尝试过的问题

标签: python mongodb aggregation-framework pymongo


【解决方案1】:

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

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

Try it here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-04
    • 2016-07-16
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 2012-06-26
    • 2018-06-16
    • 1970-01-01
    相关资源
    最近更新 更多