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

MongoDB聚合求助:按Owner/Mentor分组统计玩家数(结果不准确)

正确的MongoDB聚合管道:统计每个用户(owner/mentor)对应的玩家数量

原管道的问题

你当前的聚合逻辑错误在于使用$ifNull时,每个玩家文档只会被归属到owner_id或mentor_id中的单一用户。如果一个玩家同时拥有owner和mentor,其中一个用户的统计会被遗漏,导致结果不准确。

正确的聚合管道

我们需要将每个玩家文档拆分为两条记录(分别对应owner和mentor),再按用户ID分组统计:

db.players.aggregate([
    // 1. 将owner_id和mentor_id整理为用户ID数组
    {
        $project: {
            user_ids: ["$owner_id", "$mentor_id"]
        }
    },
    // 2. 拆分数组,每个用户ID单独成为一条文档
    { $unwind: "$user_ids" },
    // 3. 过滤掉可能的null值(如果存在无owner/mentor的玩家)
    { $match: { user_ids: { $ne: null } } },
    // 4. 按用户ID分组统计玩家数量
    {
        $group: {
            _id: "$user_ids",
            playerCount: { $sum: 1 }
        }
    },
    // 5. 调整输出格式,去除默认_id字段,改用user_id
    {
        $project: {
            user_id: "$_id",
            playerCount: 1,
            _id: 0
        }
    }
]);

步骤解释

  • $project:将每个玩家的owner和mentor ID整合到一个数组中,为后续拆分做准备。
  • $unwind:把数组拆分为独立文档,这样每个玩家对应的owner和mentor都会被单独计数。
  • $match:过滤掉数组中可能存在的null值(比如某些玩家没有设置owner或mentor的情况),避免无效统计。
  • $group:按用户ID分组,累加每个用户对应的玩家数量。
  • $project:调整输出结构,让结果更直观,用user_id替代默认的_id字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:07:08