MongoDB - 替换嵌入字段

MongoDB - Replace embedded fields

我有以下合集:

[
  {
    "_id": "6021d4e8de525e00bb3623f1",
    ...otherFields,
    "addonGroups": [
      {
        "_id": "6021d474143dbb00da601e6a",
        ...otherFields,
        "addons": [
          {
            "name": "Nike\t珍珠",
            ...otherFields,
          },
          {
            "name": "Adidas\t椰果",
            ...otherFields,
          },
          
        ]
      }
    ],
    
  }
]

我想替换所有插件名称字段中的 \t 空格字符“ ”

我有以下内容:

db.collection.aggregate([
  {
    $addFields: {
      "addonGroups.addons.name": {
        $replaceAll: {
          input: "$addonGroups.addons.name",
          find: "\t",
          replacement: " "
        }
      }
    }
  }
])

我收到这个错误:

query failed: (Location51746) PlanExecutor error during aggregation :: caused by :: $replaceAll requires that 'input' be a string, found: [["Nike 珍珠", "Adidas 椰果"]]

您可以使用 $map 运算符。

db.collection.aggregate([
  {
    $set: {
      addonGroups: {
        $map: {
          input: "$addonGroups",
          as: "addonGroup",
          in: {
            "$mergeObjects": [
              "$$addonGroup",
              {
                "addons": {
                  $map: {
                    input: "$$addonGroup.addons",
                    as: "addon",
                    in: {
                      $mergeObjects: [
                        "$$addon",
                        {
                          "name": {
                            $replaceAll: {
                              input: "$$addon.name",
                              find: "\t",
                              replacement: " "
                            }
                          }
                        }
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground