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

MongoDB聚合查询需求:添加成绩评级字段(Distinction/Fail)

修改后的MongoDB聚合查询语句

以下是实现成绩评级功能的修改后查询,通过$cond操作符完成条件判断:

db.marks.aggregate([
  {$lookup: {from:"students", localField:"StudentId", foreignField:'_id', as:"students"}},
  {$unwind: {path:"$Result"}},
  {$match: {"Result.Marks":{$gte:70}}},
  {$project: {
    _id: 0,
    "Result.Subject": 1,
    "Result.Marks": 1,
    "students.Name": 1,
    "Rating": {
      $cond: {
        if: {$gte: ["$Result.Marks", 80]},
        then: "Distinction",
        else: {
          $cond: {
            if: {$lte: ["$Result.Marks", 35]},
            then: "Fail",
            else: null // 其他分数可根据需求自定义,例如"Pass"
          }
        }
      }
    }
  }}
])

关键调整说明

  • 调整$match步骤位置:移至$unwind之后、$project之前,先过滤掉成绩低于70的记录,减少后续处理的数据量,提升查询效率。
  • 新增Rating字段:通过嵌套的$cond实现多条件判断,满足以下规则:
    • 成绩≥80时,标记为"Distinction"
    • 成绩≤35时,标记为"Fail"
    • 其他分数返回null,可根据实际需求修改为其他值(如"Pass")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:25:35