You need to enable JavaScript to run this app. MongoDB聚合中如何正确统计指定用户测验的正误答案数量
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合中如何正确统计指定用户测验的正误答案数量

问题根源
  • 原查询误用$sum操作符:$sum仅能在$group阶段对分组字段累计、或作为数组累加器处理数组元素,直接写{"$sum": "correct"}相当于对字符串常量所在的不存在的字段求和,因此固定返回0。
  • 统计逻辑未处理嵌套数组:目标是统计response数组内部的元素状态,需要先遍历/过滤数组,再计算符合条件的元素个数,原逻辑完全没有涉及数组处理。
修正后的聚合实现

(通用兼容MongoDB 3.2+版本)

const response = await Response.aggregate([
  {
    $match: {
      userID: `${userID}`,
      quizID: `${quizID}`
    }
  },
  {
    $project: {
      // 不需要保留res字段可直接删除这一行
      res: "$response.status",
      result: {
        correct: {
          // 过滤出status为correct的元素,取数组长度即为正确数
          $size: {
            $filter: {
              input: "$response",
              cond: { $eq: ["$$this.status", "correct"] }
            }
          }
        },
        incorrect: {
          // 过滤出status为wrong的元素,取数组长度即为错误数
          $size: {
            $filter: {
              input: "$response",
              cond: { $eq: ["$$this.status", "wrong"] }
            }
          }
        }
      }
    }
  }
]);

如果使用MongoDB 4.4及以上版本,可使用数组累加器$sum简化写法,无需嵌套$filter:

// 替换$project内的result字段定义即可
result: {
  correct: {
    $sum: {
      $map: {
        input: "$response",
        as: "item",
        in: { $cond: [{ $eq: ["$$item.status", "correct"] }, 1, 0] }
      }
    }
  },
  incorrect: {
    $sum: {
      $map: {
        input: "$response",
        as: "item",
        in: { $cond: [{ $eq: ["$$item.status", "wrong"] }, 1, 0] }
      }
    }
  }
}
预期返回结果

针对你提供的测试文档,修正后查询会输出:

{
  "_id": "6062e68c132e2d61d168df1d",
  "res": ["correct", "wrong", "wrong"],
  "result": {
    "correct": 1,
    "incorrect": 2
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 10:54:03