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

如何编写Mongo Query统计参会人参与活动数及与其他参会人同场次数

MongoDB参会人关联统计查询实现

假设你的集合名为events,可通过如下聚合管道实现需求,兼容MongoDB 4.0及以上版本:

db.events.aggregate([
  {
    $facet: {
      // 分支1:统计每个参会人累计参与的活动总数
      totalEventCounts: [
        { $unwind: "$attendees" },
        {
          $group: {
            _id: "$attendees",
            howManyEvents: { $sum: 1 }
          }
        }
      ],
      // 分支2:统计每对参会人共同参与活动的次数
      cooccurCounts: [
        // 复制完整参会人数组用于后续配对
        { $addFields: { allAttendees: "$attendees" } },
        // 第一次展开得到主参会人
        { $unwind: "$attendees" },
        // 第二次展开得到共同参会人
        { $unwind: "$allAttendees" },
        // 过滤掉自己和自己配对的无效数据
        {
          $match: {
            $expr: { $ne: ["$attendees", "$allAttendees"] }
          }
        },
        // 按参会人对分组统计共同出现次数
        {
          $group: {
            _id: {
              attendee: "$attendees",
              togetherWith: "$allAttendees"
            },
            howManyTimes: { $sum: 1 }
          }
        }
      ]
    }
  },
  // 展开共同参会统计结果为单条记录
  { $unwind: "$cooccurCounts" },
  // 关联对应用户的总参与活动数
  {
    $addFields: {
      userTotal: {
        $first: {
          $filter: {
            input: "$totalEventCounts",
            cond: { $eq: ["$$this._id", "$cooccurCounts._id.attendee"] }
          }
        }
      }
    }
  },
  // 调整输出字段为预期格式
  {
    $project: {
      _id: 0,
      attendee: "$cooccurCounts._id.attendee",
      howManyEvents: "$userTotal.howManyEvents",
      togetherWith: "$cooccurCounts._id.togetherWith",
      howManyTimes: "$cooccurCounts.howManyTimes"
    }
  },
  // 可选:按参会人、共同参会人排序方便查看
  { $sort: { attendee: 1, togetherWith: 1 } }
])

使用说明

  • 若需要查询特定参会人的关联数据,可在管道末尾添加$match阶段过滤,例如查询B和A的共同参与次数:
    { $match: { attendee: "B", togetherWith: "A" } }
    
  • 数据量较大时建议给attendees字段添加索引,可大幅提升查询效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:15:03