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

MongoDB聚合查询:嵌套数组匹配投影空数组问题排查

问题原因分析

直接用$array1.array2作为$filter的input时,得到的是二维数组(每个array1元素的array2子数组组成的数组)。$filter遍历的是这个二维数组的每一项(也就是每个array2子数组),而非子数组内的单个对象。此时$$response指向整个子数组,不存在key3属性,导致过滤条件永远不成立,最终返回空数组。

解决方案

要实现需求,需先将二维数组展平为一维,再执行过滤、去重和投影操作。以下是两种可行的聚合管道写法:

方法一:用$unwind展开数组(直观易读)

[
  { $unwind: "$array1" },
  { $unwind: "$array1.array2" },
  { $match: { "array1.array2.key3": "value4" } },
  { $group: { _id: null, target: { $first: "$array1.array2" } } },
  { $project: { _id: 0, key1: "$target.key1", key2: "$target.key2" } }
]

方法二:用聚合表达式(单阶段逻辑整合)

[
  {
    $project: {
      flattened: {
        $reduce: {
          input: "$array1",
          initialValue: [],
          in: { $concatArrays: ["$$value", "$$this.array2"] }
        }
      }
    }
  },
  {
    $project: {
      filtered: {
        $filter: {
          input: "$flattened",
          as: "item",
          cond: { $eq: ["$$item.key3", "value4"] }
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      key1: { $arrayElemAt: ["$filtered.key1", 0] },
      key2: { $arrayElemAt: ["$filtered.key2", 0] }
    }
  }
]

两种方法最终都会输出预期结果:

{ "key1": "value_1", "key2": "value_2" }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:31:05