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

MongoDB深度嵌套数组过滤:筛选含1或5的array2元素

MongoDB嵌套数组筛选解决方案

问题场景

现有集合数据:

[{
  "array1": [{
    "array2": [{
      "array3": [1, 2]
    }, {
      "array3": [2, 3]
    }, {
      "array3": [3, 4]
    }, {
      "array3": [4, 5]
    }]
  }]
}]

需筛选出array2中array3包含1或5的元素,期望输出:

[{
  "array1": [{
    "array2": [{
      "array3": [1, 2]
    }, {
      "array3": [4, 5]
    }]
  }]
}]

原代码问题

原聚合管道错误使用$in运算符:

db.collection.aggregate([{
  "$project": {
    "array1.array2": {
      $filter: {
        "input": "$array1.array2",
        "cond": {
          "$in": ["$$this.array3", [1, 5]]
        }
      }
    }
  }
}])

错误原因:$in的语法是$in: [ <value>, <array> ],原代码将整个array3数组作为<value>去匹配[1,5]中的元素,逻辑不成立,导致筛选结果为空。同时未处理array1本身是数组的情况,直接对$array1.array2做$filter不符合嵌套数组的遍历逻辑。

正确解决方案

方法一:$or结合$in精准匹配

通过$map遍历外层的array1,再对每个array1元素内的array2做$filter,用$or分别检查1和5是否存在于array3中:

db.collection.aggregate([
  {
    "$project": {
      "array1": {
        "$map": {
          "input": "$array1",
          "as": "item1",
          "in": {
            "array2": {
              "$filter": {
                "input": "$$item1.array2",
                "cond": {
                  "$or": [
                    {"$in": [1, "$$this.array3"]},
                    {"$in": [5, "$$this.array3"]}
                  ]
                }
              }
            }
          }
        }
      }
    }
  }
])

方法二:$anyElementTrue批量检查

使用$anyElementTrue结合$map,批量检查目标值(1、5)是否有任意一个存在于array3中:

db.collection.aggregate([
  {
    "$project": {
      "array1": {
        "$map": {
          "input": "$array1",
          "as": "item1",
          "in": {
            "array2": {
              "$filter": {
                "input": "$$item1.array2",
                "cond": {
                  "$anyElementTrue": {
                    "$map": {
                      "input": [1, 5],
                      "as": "target",
                      "in": {"$in": ["$$target", "$$this.array3"]}
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:44:58