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

MongoDB聚合查询:合并嵌套steps下所有actions为单个数组

修改后的聚合查询代码

db.getCollection("missions").aggregate([
    {
        $match: {
            _id: ObjectId("6045eec8f113547ddd3472d9")
        }
    },
    {
        $addFields: {
            "allActions": {
                $reduce: {
                    input: "$execution.steps",
                    initialValue: [],
                    in: { $concatArrays: ["$$value", "$$this.actions"] }
                }
            }
        }
    },
    // 可选阶段:如果不需要保留原execution等其他字段,可加该阶段过滤输出
    {
        $project: {
            allActions: 1
        }
    }
])

逻辑说明

你原有代码的问题是直接将steps数组赋值给了allActions,没有提取每个step下嵌套的actions数组。修改后的方案:

  • 通过$reduce操作符遍历execution.steps数组,初始累加值设为空数组
  • 每次遍历拿到当前step对象(对应变量$$this),通过$concatArrays将当前step的actions数组合并到累加结果(对应变量$$value)中
  • 最终直接得到所有step下所有action归集后的扁平数组,和你预期的输出结构完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:30:02