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

如何在MongoDB中获取最大值对应的字段名?

获取MongoDB文档中的最高分及对应科目

针对你给出的文档结构,要同时拿到最高分和对应的科目名称,可以通过MongoDB的聚合管道来实现,下面提供两种实用方案:

方案一:用$reduce直接定位最高分科目

这种方法通过一次遍历数组就能锁定分数最高的科目,效率较高:

db.collection.aggregate([
  // 构造科目与分数的键值对数组
  {
    $addFields: {
      subjects: [
        { subject: "math", score: "$math" },
        { subject: "sci", score: "$sci" },
        { subject: "hindi", score: "$hindi" },
        { subject: "physics", score: "$physics" }
      ]
    }
  },
  // 遍历数组,保留分数最高的科目信息
  {
    $addFields: {
      top_subject: {
        $reduce: {
          input: "$subjects",
          initialValue: { subject: "", score: -1 },
          in: {
            $cond: [
              { $gt: ["$$this.score", "$$value.score"] },
              "$$this",
              "$$value"
            ]
          }
        }
      }
    }
  },
  // 整理输出需要的字段
  {
    $project: {
      _id: 0,
      name: 1,
      max_score: "$top_subject.score",
      subject_name: "$top_subject.subject"
    }
  }
])

执行后返回结果示例:

{ "name" : "Suresh", "max_score" : 96.0, "subject_name" : "hindi" }

方案二:先算最高分再匹配对应科目

这种方法逻辑更直观,先拿到最高分,再筛选出对应科目:

db.collection.aggregate([
  // 构造科目与分数的键值对数组
  {
    $addFields: {
      subjects: [
        { subject: "math", score: "$math" },
        { subject: "sci", score: "$sci" },
        { subject: "hindi", score: "$hindi" },
        { subject: "physics", score: "$physics" }
      ]
    }
  },
  // 计算所有科目的最高分
  {
    $addFields: {
      max_score: { $max: "$subjects.score" }
    }
  },
  // 筛选出分数等于最高分的科目
  {
    $addFields: {
      top_subjects: {
        $filter: {
          input: "$subjects",
          cond: { $eq: ["$$this.score", "$max_score"] }
        }
      }
    }
  },
  // 提取科目名称并整理输出
  {
    $project: {
      _id: 0,
      name: 1,
      max_score: 1,
      subject_name: { $arrayElemAt: ["$top_subjects.subject", 0] }
    }
  }
])

如果存在多个科目同分的情况,$arrayElemAt会取第一个匹配的科目;若需要返回所有同分科目,直接保留top_subjects字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:57:32