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

MongoDB使用自定义键实现$arrayToObject数组转对象的方法

实现方案

你可以在现有聚合管道后追加一个$set(或$addFields/$project)阶段,结合$reduce/$map + $arrayToObject实现格式转换,完整代码如下:

db.your_collection.aggregate([
  // 此处保留你之前生成原始results数组的所有聚合阶段
  {
    $set: {
      results: {
        $arrayToObject: {
          $reduce: {
            input: "$results",
            initialValue: [],
            in: {
              $concatArrays: [
                "$$value",
                [
                  { k: { $concat: ["$$this.status", "_footage"] }, v: "$$this.footage" },
                  { k: { $concat: ["$$this.status", "_pieces"] }, v: "$$this.pieces" }
                ]
              ]
            }
          }
        }
      }
    }
  }
])

逻辑说明

  • $reduce遍历原始results数组,每次迭代将当前元素的status字段值分别与footage、pieces拼接为键,对应字段值作为值,生成两个符合$arrayToObject输入要求的{k: 键名, v: 键值}格式对象
  • 用$concatArrays将每次迭代生成的kv对象追加到累计数组中,最终得到所有kv对组成的一维数组
  • 最后$arrayToObject将kv数组直接转换为你需要的扁平化对象结构

你也可以用$map替换$reduce实现相同效果,写法更简洁:

{
  $set: {
    results: {
      $arrayToObject: {
        $concatArrays: {
          $map: {
            input: "$results",
            in: [
              { k: { $concat: ["$$this.status", "_footage"] }, v: "$$this.footage" },
              { k: { $concat: ["$$this.status", "_pieces"] }, v: "$$this.pieces" }
            ]
          }
        }
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者13z_coder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 07:39:04