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

MongoDB如何匹配数组字段包含另一数组所有值的文档?

MongoDB筛选数组字段包含另一数组字段的文档

示例数据

db={
  "Test": [
    {
      "x": [1, 2],
      "y": [1, 2, 3]
    },
    {
      "x": [1, 2],
      "y": [2, 3, 4]
    }
  ]
}

静态数组值匹配方法

匹配静态数组值时,可通过$all操作符筛选出y数组包含指定所有值的文档:

db.Test.aggregate([
  {
    "$match": {
      "y": {
        "$all": [1, 2]
      }
    }
  }
])

执行后得到预期结果:

[
  {
    "x": [1, 2],
    "y": [1, 2, 3]
  }
]

动态字段匹配的问题

需要筛选y数组包含x数组所有值的文档时,直接在$expr中使用$all会报错,因为$all不支持在表达式上下文里以这种方式引用字段:

db.Test.aggregate([
  {
    "$match": {
      "$expr": {
        "$all": [
          "$x",
          "$y"
        ]
      }
    }
  }
])

替代方案

方案1:使用$setIsSubset

$setIsSubset可判断第一个数组是否是第二个数组的子集,完全满足“x的所有元素都存在于y中”的需求:

db.Test.aggregate([
  {
    "$match": {
      "$expr": {
        "$setIsSubset": ["$x", "$y"]
      }
    }
  }
])

方案2:使用$reduce遍历检查

如果需要处理重复元素等更复杂的场景,可通过$reduce遍历x数组,逐个验证元素是否存在于y中:

db.Test.aggregate([
  {
    "$match": {
      "$expr": {
        "$reduce": {
          "input": "$x",
          "initialValue": true,
          "in": {
            "$and": [
              "$$value",
              { "$in": ["$$this", "$y"] }
            ]
          }
        }
      }
    }
  }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:42:39