用mongodb中的聚合替换js代码

时间:2018-02-18 18:59:36

标签: javascript mongodb aggregation-framework

我有一个名为groups的mongo文档。这是一系列的学生和科目。 每个科目都有一系列的课程。 每节课都有一系列标记。

通常,文档如下所示:

[
  {
    "students": [
      { "_id": "0", "firstName": "Bob", "lastName": "Jhonson" },
      { "_id": "1", "firstName": "Jackie", "lastName": "Chan" }
      // other students ...
    ],
    "subjects": [
      {
        "name": "Algebra",
        "lessons": [
          {
            "date": 1489363200,
            "marks": [
              { "student_id": "0", "value": 5 },
              { "student_id": "1", "value": 4 }
              // other marks...
            ]
          }, {
            "date": 1489622400,
            "marks": [
              { "student_id": "0", "value": 3 },
              { "student_id": "1", "value": 2 }
              // other marks...
            ]
          }
          // other lessons...
        ]
      }
    ]
  }
]

然后我用js函数将这些数据转换成这样的东西:

[
  {
    "_id": "5a89ca11abc4ffd25a430420",
    "subjects": [
      {
        "name": "Algebra",
        "dates": [1489363200, 1489622400],
        "students": [
          {
            "_id": "0",
            "firstName": "Bob",
            "lastName": "Jhonson",
            "marks": [ 5, 3 ]
          },
          {
            "_id": "1",
            "firstName": "Jackie",
            "lastName": "Chan",
            "marks": [ 4, 2 ]
          }
        ]
      }
    ]
  }
]

转换json文档的函数:

function transformData (groups) { // groups - array
  let newGroups = [];

  for (let group of groups) {
    newGroup = {};

    for (let key in group) {
      if (key === 'students' || key === 'subjects') continue;
      newGroup[key] = group[key];
    }
    newGroup.subjects = [];

    for (let subject of group.subjects) {
      let newSubject = {
        name: subject.name,
        dates: [],
        students: []
      };

      for (let student of group.students) {
        let index = newSubject.students.push(student) - 1;
        newSubject.students[index].marks = [];
      }

      for (let lesson of subject.lessons) {
        let index = newSubject.dates.push(lesson.date) - 1;

        for (let mark of lesson.marks) {
          for (let student of newSubject.students) {
            if (student._id !== mark.student_id) continue;

            while(student.marks.length !== index) {
              student.marks.push(null);
            }
            student.marks.push(mark.value);
          }
        }
      }

      newGroup.subjects.push(newSubject);
    }

    newGroups.push(newGroup);
  }

  return newGroups;
}

如何用mongodb聚合替换此函数?

0 个答案:

没有答案