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

MongoDB中从嵌套数组提取值及其索引的聚合实现

MongoDB 嵌套二维数组匹配并获取行列索引方案

需求回顾

给定嵌套数组文档:

[
  {
    "rows": [["123", "234", "345"], ["345", "456", "567"]]
  },
  {
    "rows": [["111", "222", "333"], ["444", "555", "345"]]
  }
]

需聚合得到包含目标值(如345)、行索引row_i、列索引col_i的结果:

[
  {"value": "345", "row_i": 0, "col_i": 2},
  {"value": "345", "row_i": 1, "col_i": 0},
  {"value": "345", "row_i": 1, "col_i": 2}
]

实现方案

通过MongoDB聚合管道的多阶段组合完成,无需修改原数据结构:

db.your_collection.aggregate([
  // 展开rows数组,同时获取行索引
  {
    $unwind: {
      path: "$rows",
      includeArrayIndex: "row_i"
    }
  },
  // 遍历当前行元素,筛选目标值并记录列索引
  {
    $addFields: {
      matched_cols: {
        $filter: {
          input: {
            $map: {
              input: "$rows",
              as: "col_val",
              in: {
                value: "$$col_val",
                col_i: { $indexOfArray: ["$rows", "$$col_val"] }
              }
            }
          },
          cond: { $eq: ["$$this.value", "345"] }
        }
      }
    }
  },
  // 展开匹配的列结果数组
  { $unwind: "$matched_cols" },
  // 格式化输出所需字段
  {
    $project: {
      _id: 0,
      value: "$matched_cols.value",
      row_i: "$row_i",
      col_i: "$matched_cols.col_i"
    }
  }
])

关键阶段说明

  • $unwind带索引:通过includeArrayIndex参数直接获取当前元素在rows数组中的行索引,赋值给row_i;
  • $map+$filter组合:$map遍历每行的所有元素,用$indexOfArray获取元素的列索引;$filter只保留值等于目标值的条目;
  • 二次$unwind:将每行的匹配列数组展开为独立文档;
  • $project:剔除不需要的字段,整理成需求指定的输出结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:33:34