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

MongoDB聚合查询:将frame_id字段移入数组每个元素中

解决方案

你可以在现有聚合管道的末尾添加$set(或$addFields)阶段,通过$map操作符遍历sections数组,将当前文档的frame_id注入到数组的每个元素中,再用$project移除顶层的frame_id字段。

修改后的完整聚合查询如下:

db['foo'].aggregate([
  { $project: {
      frame: {
          frame_id: "$frameProfileId",
          sections: {
              $filter: {
                  input: "$sections",
                  cond: { $eq: [ "$$frameSection.metadata.subType", "Quaternion"] },
                  as: "frameSection"
              }
          }
      }
  }},
  { $unwind: "$frame"},
  { $replaceRoot: { newRoot: "$frame"}},
  // 新增:给sections每个元素添加frame_id
  { $set: {
      sections: {
          $map: {
              input: "$sections",
              as: "item",
              in: { $mergeObjects: [ "$$item", { frame_id: "$frame_id" } ] }
          }
      }
  }},
  // 移除顶层冗余的frame_id
  { $project: { frame_id: 0 }}
])

关键逻辑说明:

  • $map遍历数组:逐个处理sections里的元素,用$mergeObjects把原元素和frame_id字段合并,避免手动列举所有字段的麻烦,后续元素新增字段也能自动兼容。
  • $project清理字段:最后剔除顶层的frame_id,只保留处理后的sections数组结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:05:19