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

MongoDB聚合中使用$count统计数组交集元素数量

嘿,这个需求我熟!咱们用MongoDB的聚合管道就能轻松搞定,核心就是先找出两个数组的交集,再统计交集的长度,要是需要统计符合特定条件的文档总数,再用上$count就行。给你一步步拆解:

1. 为每个文档计算交集元素数量

如果你要给cars集合里的每篇文档,都算出topDesigners和当前文档designers数组的交集个数,用下面的聚合管道就可以:

db.cars.aggregate([
  // 先把你的topDesigners数组注入到每个文档里(按需替换成实际数组)
  {
    $addFields: {
      topDesigners: ["Brad Johnson", "Kevin Williams", "John Smith"]
    }
  },
  // 计算designers和topDesigners的交集
  {
    $addFields: {
      matchingDesigners: { $setIntersection: ["$designers", "$topDesigners"] }
    }
  },
  // 统计交集的长度,得到咱们要的count值
  {
    $project: {
      _id: 1, // 保留原文档ID,不需要的话可以删掉
      designers: 1,
      count: { $size: "$matchingDesigners" }
    }
  }
])

2. 用$count统计符合条件的文档总数

要是你的需求不止于单个文档的count,还要统计集合里满足“count等于某个值”的文档总数(比如统计有多少个文档的交集数量是2),可以在上面的管道后追加$match和$count阶段:

db.cars.aggregate([
  { $addFields: { topDesigners: ["Brad Johnson", "Kevin Williams", "John Smith"] } },
  { $addFields: { matchingDesigners: { $setIntersection: ["$designers", "$topDesigners"] } } },
  { $project: { count: { $size: "$matchingDesigners" } } },
  // 筛选出count为2的文档
  { $match: { count: 2 } },
  // 统计这类文档的总数,结果字段名可以自定义
  { $count: "totalDocsWithCount2" }
])

对应你的示例验证

咱们拿你给的例子测试一下,完全符合预期:

  • 当designers是["Kevin Williams", "Jane Smith"]时,交集只有["Kevin Williams"],count=1;
  • 当designers是["Jane Smith", "John Smith"]时,交集是["John Smith"],count=1;
  • 当designers是["Kevin Huntzberger", "Brad Johnson", "John Smith"]时,交集是["Brad Johnson", "John Smith"],count=2;

小提示

  • 如果topDesigners不是固定数组,而是来自另一个集合或者外部变量,可以用$lookup关联集合,或者通过聚合变量的方式传入;
  • 要是不需要保留原文档的其他字段,直接在$project里只留count就行,或者用$replaceRoot把结果替换成仅包含count的文档。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:25:51