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

MongoDB如何通过聚合查询获取每个学生最高的两个考试分数

解法1:MongoDB 5.2+ 最简方案(用$sortArray运算符)

直接在$project阶段完成数组排序、截取、值提取,不需要拆分重组数组,性能更高:

db.student.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      maxExams: {
        $map: {
          // 对examScores按score降序排序后取前2个元素
          input: {
            $slice: [
              { $sortArray: { input: "$examScores", sortBy: { score: -1 } } },
              2
            ]
          },
          in: "$$this.score" // 仅提取score字段值组成新数组
        }
      }
    }
  }
])

解法2:兼容所有MongoDB版本的通用方案

如果你的MongoDB版本低于5.2,不支持$sortArray,可以用拆分-排序-分组-截取的流程实现:

db.student.aggregate([
  // 保留需要的字段,过滤冗余数据
  {
    $project: {
      name: 1,
      examScores: 1
    }
  },
  // 拆分examScores数组为独立单条文档
  { $unwind: "$examScores" },
  // 先按学生分组排序,再按分数降序排序,保证每个学生的分数从高到低排列
  { $sort: { name: 1, "examScores.score": -1 } },
  // 按学生分组,把排序后的分数依次存入maxExams数组
  {
    $group: {
      _id: "$name",
      maxExams: { $push: "$examScores.score" }
    }
  },
  // 格式化输出结果,截取前2个最高分
  {
    $project: {
      _id: 0,
      name: "$_id",
      maxExams: { $slice: ["$maxExams", 2] }
    }
  }
])

两种方案执行后都会返回你要求的格式结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:24:02