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

如何在MongoDB中通过聚合操作合并数组对象的字段

MongoDB聚合合并数组中相同乘客区间的价格记录

你可以通过以下MongoDB聚合管道实现需求,将相同min_pax和max_pax区间的价格记录合并,把One Way和Round Trip的价格转为独立字段:

db.collection.aggregate([
  // 展开prices数组,将每个价格对象转为单独文档
  { $unwind: "$prices" },
  // 按tipo、min_pax、max_pax分组,提取对应类型的价格
  {
    $group: {
      _id: {
        tipo: "$tipo",
        min_pax: "$prices.min_pax",
        max_pax: "$prices.max_pax"
      },
      one_way: {
        $first: {
          $cond: [{ $eq: ["$prices.type", "One Way"] }, "$prices.price", null]
        }
      },
      round_trip: {
        $first: {
          $cond: [{ $eq: ["$prices.type", "Round Trip"] }, "$prices.price", null]
        }
      }
    }
  },
  // 按tipo重新分组,将合并后的价格记录整理为prices数组
  {
    $group: {
      _id: "$_id.tipo",
      prices: {
        $push: {
          min_pax: "$_id.min_pax",
          max_pax: "$_id.max_pax",
          one_way: "$one_way",
          round_trip: "$round_trip"
        }
      }
    }
  },
  // 重命名字段,匹配期望的输出格式
  {
    $project: {
      _id: 0,
      tipo: "$_id",
      prices: 1
    }
  }
])

步骤说明:

  • $unwind:将原文档中的prices数组拆分为多个文档,每个文档包含原tipo和单个prices对象,方便后续分组处理。
  • 第一次$group:以tipo、min_pax、max_pax为分组键,使用$cond判断价格类型,提取对应价格值(每个区间只有两种类型,用$first即可拿到对应值)。
  • 第二次$group:以tipo为分组键,通过$push将第一次分组得到的每个区间价格记录重新组合成prices数组。
  • $project:移除默认的_id字段,将分组键_id重命名为tipo,确保输出格式和期望一致。

执行上述聚合后,就能得到你需要的合并后的结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:30:51