MongoDB 中聚合统计计算(2)

{ "_id": 1, "quizzes": [ 10, 6, 7 ], "labs": [ 5, 8 ], "final": 80, "midterm": 75 }
{ "_id": 2, "quizzes": [ 9, 10 ], "labs": [ 8, 8 ], "final": 95, "midterm": 80 }
{ "_id": 3, "quizzes": [ 4, 5, 5 ], "labs": [ 6, 5 ], "final": 78, "midterm": 70 }

现在的需求是统计每个学生的 平常的测验分数总和、实验分数总和、期末其中分数总和。

db.students.aggregate([
  {
    $project: {
      quizTotal: { $sum: "$quizzes"},
      labTotal: { $sum: "$labs" },
      examTotal: { $sum: [ "$final", "$midterm" ] }
    }
  }
])

其查询输出结果如下:

{ "_id" : 1, "quizTotal" : 23, "labTotal" : 13, "examTotal" : 155 }
{ "_id" : 2, "quizTotal" : 19, "labTotal" : 16, "examTotal" : 175 }
{ "_id" : 3, "quizTotal" : 14, "labTotal" : 11, "examTotal" : 148 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/3a6684049ae16c5be701d49c74809c95.html