/** * Update student records and set their average test score and grade * computed from that average. */ // update every student record db.students.updateMany( {}, [ // Compute the average of all the test scores and set that as the `average` field { $set: { average : { $trunc: [ { $avg: "$tests" }, 0 ] } } }, // Then set the `grade` field based on that average { $set: { grade: { $switch: { branches: [ { case: { $gte: [ "$average", 90 ] }, then: "A" }, { case: { $gte: [ "$average", 80 ] }, then: "B" }, { case: { $gte: [ "$average", 70 ] }, then: "C" }, { case: { $gte: [ "$average", 60 ] }, then: "D" } ], default: "F" } } } } ] );