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

MongoDB如何按两个数组同索引第0位元素对应分组查询

MongoDB同索引配对st、en数组的聚合实现

实现逻辑

  • 先计算数组总长度作为total_index_count字段
  • 用$zip运算符将st、en两个数组按索引位置两两配对
  • 拆分配对后的数组,每组配对生成独立文档
  • 按期望格式重构输出字段

具体聚合语句

db.你的集合名.aggregate([
  {
    $addFields: {
      // 统计数组总长度,前提是st和en长度一致
      total_index_count: { $size: "$st" }
    }
  },
  {
    $addFields: {
      // 按索引配对st、en的元素
      paired_list: {
        $zip: {
          inputs: ["$st", "$en"]
        }
      }
    }
  },
  // 拆分配对列表为独立文档
  { $unwind: "$paired_list" },
  {
    $project: {
      _id: 0,
      // 提取st字段与对应值
      st: { $arrayElemAt: [ { $arrayElemAt: ["$paired_list", 0] }, 0 ] },
      st_val: { $arrayElemAt: [ { $arrayElemAt: ["$paired_list", 0] }, 1 ] },
      // 提取en字段与对应值
      en: { $arrayElemAt: [ { $arrayElemAt: ["$paired_list", 1] }, 0 ] },
      en_val: { $arrayElemAt: [ { $arrayElemAt: ["$paired_list", 1] }, 1 ] },
      total_index_count: 1
    }
  }
])

版本兼容说明

如果你的MongoDB版本≥4.4,可以用$first/$last简化字段提取逻辑,写法更易读:

// 对应project阶段的字段提取部分
st: { $first: { $first: "$paired_list" } },
st_val: { $last: { $first: "$paired_list" } },
en: { $first: { $last: "$paired_list" } },
en_val: { $last: { $last: "$paired_list" } },

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:24:02