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

如何在MongoDB聚合查询中使用$setIntersection实现多个数组取交集

解决方案

你当前的写法中$setIntersection接收的参数是$data这一整个嵌套数组(结构为[[第一个学生数组], [第二个学生数组], ...]),而$setIntersection的语法要求传入多个独立的数组参数才能计算多数组的交集,因此无法得到预期结果。

修改后的聚合语句

你可以使用$reduce迭代data数组,逐次计算交集,修改后的聚合查询如下:

aggregate([
  {
    $match: {
      class: {
        $in: classes,
      },
    },
  },
  {
    $project: { students: 1 },
  },
  {
    $group: {
      _id: null,
      count: { $sum: 1 },
      data: { $push: "$students" },
    },
  },
  {
    $project: {
      count: 1,
      students: {
        $cond: {
          if: { $eq: ["$count", 0] },
          then: [],
          else: {
            $reduce: {
              input: "$data",
              initialValue: { $arrayElemAt: ["$data", 0] },
              in: { $setIntersection: ["$$value", "$$this"] }
            }
          }
        }
      },
    },
  },
])

逻辑说明

  • 用$reduce遍历data里的所有学生数组,初始值取第一个学生数组
  • 每轮迭代都将上一轮得到的交集结果,和当前遍历到的学生数组重新计算交集
  • 新增了$cond判断处理无匹配班级的边界情况,避免报错

内容的提问来源于stack exchange,提问作者Tlaloc-ES

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:36:05