【问题标题】:Mongo Aggregate Function to sum variables in collection that match queryMongo聚合函数对集合中匹配查询的变量求和
【发布时间】:2021-06-30 08:11:36
【问题描述】:

我有以下数据集,其中包含学生考试的分数。但是,对于test 的每个问题,每个mark 都存储在一个单独的对象中,如下所示:

  {
    school: A,
    question: 1,
    student: 1,
    test: Summer Test,
    mark: 0,
  },
  {
    school: A,
    question: 2,
    student: 1,
    test: Summer Test,
    mark: 1,
  },
  {
    school: A,
    question: 3,
    student: 1,
    test: Summer Test,
    mark: 2,
  },

如何使用 mongo 聚合来计算学生在特定考试中获得的分数,方法是将所有单独的分数相加?然后按school分组? 所以结果应该是这样的:

**school A**    
{
   Summer Test {
      students: {student 1 = 3 marks; student 2 = 0 marks; student 3 = 2 marks}
   }
   Winter Test {
      students: {student 1 = 2 marks; student 2 = 1 marks; student 3 = 3 marks}
   }
}

对于每个school 等等?谁能给我一些关于如何解决这个问题的建议?非常感谢

【问题讨论】:

  • 您的学生 id 在全球范围内是唯一的还是学生 id 是学校级别的,因此可以在每所学校重复使用

标签: javascript mongodb aggregation-framework


【解决方案1】:
  • $group by school, teststudent 和总和 mark
  • $group by schooltest 并在键值对中构造students 的数组
  • $arrayToObject 以上students 数组转换为对象
  • $group 唯一由school 和键值对构造tests 的数组
  • $project 显示必填字段并将tests 数组转换为对象
db.collection.aggregate([
  {
    $group: {
      _id: {
        school: "$school",
        test: "$test",
        student: "$student"
      },
      mark: { $sum: "$mark" }
    }
  },
  {
    $group: {
      _id: {
        school: "$_id.school",
        test: "$_id.test"
      },
      students: {
        $push: {
          k: { $toString: "$_id.student" },
          v: "$mark"
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id.school",
      tests: {
        $push: {
          k: "$_id.test",
          v: { $arrayToObject: "$students" }
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      school: "$_id",
      tests: { $arrayToObject: "$tests" }
    }
  }
])

Playground

【讨论】:

    【解决方案2】:
    db.collection.aggregate([
      {
        //first group by school and test (so we get students outcome per test and school)
        $group: {
          _id: {
            school: "$school",
            test: "$test"
          },
          students: {
            $push: {
              question: "$question",
              student: "$student",
              mark: "$mark"
            }
          }
        }
      },
      //group again, so we can get tests (summer/winter) grouped by school this time
      {
        $group: {
          _id: "$_id.school",
          tests: {
            $push: {
              test: "$_id.test",
              students: "$students"
            }
          }
        }
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2020-01-13
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多