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

如何在MongoDB中过滤三层深度嵌套数组数据?

MongoDB三层嵌套数组过滤方案

要实现对包含三层嵌套数组的集合进行精准过滤,同时保留嵌套数组中的匹配项,你需要使用聚合管道来逐层处理嵌套结构,以下是具体的实现方案:

聚合查询代码

db.collection.aggregate([
  // 第一步:先过滤出存在符合条件的嵌套文档的父文档,缩小处理范围
  {
    $match: {
      "array1.name": "john",
      "array1.array2.city": "mexico",
      "array1.array2.array3.status": "verified"
    }
  },
  // 第二步:逐层过滤嵌套数组,只保留匹配的子项
  {
    $project: {
      array1: {
        $filter: {
          input: "$array1",
          as: "a1",
          cond: { $eq: ["$$a1.name", "john"] }
        }
      }
    }
  },
  {
    $addFields: {
      array1: {
        $map: {
          input: "$array1",
          as: "a1",
          in: {
            name: "$$a1.name",
            array2: {
              $filter: {
                input: "$$a1.array2",
                as: "a2",
                cond: { $eq: ["$$a2.city", "mexico"] }
              }
            }
          }
        }
      }
    }
  },
  {
    $addFields: {
      array1: {
        $map: {
          input: "$array1",
          as: "a1",
          in: {
            name: "$$a1.name",
            array2: {
              $map: {
                input: "$$a1.array2",
                as: "a2",
                in: {
                  city: "$$a2.city",
                  array3: {
                    $filter: {
                      input: "$$a2.array3",
                      as: "a3",
                      cond: { $eq: ["$$a3.status", "verified"] }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  // 可选:过滤掉array1或嵌套数组为空的文档(如果需要)
  {
    $match: {
      "array1.array2.array3": { $ne: [] }
    }
  }
])

代码解释

  1. $match 阶段:先筛选出包含name: "john"、city: "mexico"、status: "verified"的父文档,避免对无关文档做后续处理,提升效率。
  2. 第一层$project + $filter:过滤array1,只保留name为"john"的子项。
  3. 第二层$addFields + $map + $filter:遍历过滤后的array1,对每个子项的array2进行过滤,只保留city为"mexico"的子项。
  4. 第三层$addFields + $map + $filter:遍历过滤后的array2,对每个子项的array3进行过滤,只保留status为"verified"的子项。
  5. 最后一个$match(可选):如果需要排除那些经过过滤后嵌套数组为空的文档,可以加上这个阶段。

测试结果

针对你提供的示例文档,执行上述聚合查询后,会得到预期输出:

{
  "_id": "111",
  "array1": [
    {
      "name": "john",
      "array2": [
        {
          "city": "mexico",
          "array3": [
            {
              "address": "address1",
              "status": "verified"
            }
          ]
        }
      ]
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:37:26