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

如何使用Mongoose的updateMany将8个指定字段值存入desalinations数组

Mongoose updateMany实现字段值转存数组方案
  • 首先确认你的MongoDB服务版本 >=4.2,该版本才支持在update类操作中使用聚合管道读取同文档字段完成更新
  • 你现有Schema中desalinations数组元素类型为Schema.Types.ObjectId,请确保DesalinationT1 ~ DesalinationT8存储的是合法ObjectId字符串,否则类型转换会触发更新失败

基础实现代码

const Facility = mongoose.model('Facility', facilitySchema);

// 执行批量更新
await Facility.updateMany(
  // 过滤条件,空对象代表匹配所有facility文档,可按需添加自定义过滤规则
  {},
  // 聚合管道实现同文档字段读取更新
  [
    {
      $set: {
        desalinations: [
          { $toObjectId: "$DesalinationT1" },
          { $toObjectId: "$DesalinationT2" },
          { $toObjectId: "$DesalinationT3" },
          { $toObjectId: "$DesalinationT4" },
          { $toObjectId: "$DesalinationT5" },
          { $toObjectId: "$DesalinationT6" },
          { $toObjectId: "$DesalinationT7" },
          { $toObjectId: "$DesalinationT8" }
        ]
      }
    }
  ]
)

可选优化方案

如果部分DesalinationT*字段可能为空/不存在,可通过$filter过滤无效值,避免数组中出现null:

await Facility.updateMany(
  {},
  [
    {
      $set: {
        desalinations: {
          $filter: {
            input: [
              { $toObjectId: "$DesalinationT1" },
              { $toObjectId: "$DesalinationT2" },
              { $toObjectId: "$DesalinationT3" },
              { $toObjectId: "$DesalinationT4" },
              { $toObjectId: "$DesalinationT5" },
              { $toObjectId: "$DesalinationT6" },
              { $toObjectId: "$DesalinationT7" },
              { $toObjectId: "$DesalinationT8" }
            ],
            cond: { $ne: ["$$this", null] }
          }
        }
      }
    }
  ]
)

如果你后续调整Schema为desalinations数组存储String类型,把代码里的$toObjectId:前缀去掉,直接写"$DesalinationT1"即可。

内容的提问来源于stack exchange,提问作者Jake Lund

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:24:07