You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB集合迁移脚本求助:将Error字段转为数组

处理MongoDB集合中List数组内Error字段类型转换的迁移脚本

一、过滤条件

要定位需要更新的文档,需匹配List数组中存在字符串类型Error字段的文档,过滤条件如下:

{
  "List": {
    "$elemMatch": {
      "Error": { "$type": "string" }
    }
  }
}
  • $elemMatch:匹配数组中至少有一个元素满足指定条件
  • $type: "string":精准匹配Error字段为字符串类型的元素

二、更新操作逻辑

使用MongoDB聚合管道完成更新,通过$map遍历List数组,对每个元素判断Error字段类型:如果是字符串则转为单元素数组,否则保持原结构(包括无Error字段的元素)。核心更新管道如下:

[
  {
    "$set": {
      "List": {
        "$map": {
          "input": "$List",
          "as": "item",
          "in": {
            "$cond": [
              { "$eq": [{ "$type": "$$item.Error" }, "string"] },
              { "$mergeObjects": ["$$item", { "Error": ["$$item.Error"] }] },
              "$$item"
            ]
          }
        }
      }
    }
  }
]
  • $map:遍历List数组的每个元素
  • $cond:条件判断,检查当前元素的Error是否为字符串
  • $mergeObjects:保留原元素的所有字段,仅替换Error字段为数组格式
  • 无Error字段或Error已为数组的元素,直接返回原结构

三、完整updateMany脚本(Mongo Shell)

db.yourCollectionName.updateMany(
  // 过滤条件
  {
    "List": {
      "$elemMatch": {
        "Error": { "$type": "string" }
      }
    }
  },
  // 更新管道
  [
    {
      "$set": {
        "List": {
          "$map": {
            "input": "$List",
            "as": "item",
            "in": {
              "$cond": [
                { "$eq": [{ "$type": "$$item.Error" }, "string"] },
                { "$mergeObjects": ["$$item", { "Error": ["$$item.Error"] }] },
                "$$item"
              ]
            }
          }
        }
      }
    }
  ],
  // 可选:开启dryRun验证更新匹配的文档数量,不实际执行更新
  { dryRun: true }
)

四、注意事项

  • 替换yourCollectionName为实际集合名称
  • 先执行带dryRun: true的版本,验证匹配的文档数量是否符合预期
  • 建议在测试环境完成验证后,再在生产环境执行更新
  • 如果使用Node.js驱动,语法逻辑一致,只需调整为驱动对应的调用方式

内容的提问来源于stack exchange,提问作者Markus Benz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:40:45