且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用子文档数组更新 MongoDB 文档

更新时间:2022-11-13 22:38:03

有几种方法我会逐点回答

There are a few way to do this I'll answer point by point

检索所有学生或特定学生的分数(检索分数数组中的特定元素)

Class.findOne({ name: 'Grade 5 - Section A'})
     .populate('scores.studentId')
     .exec(function(err, class) {
       if (err) throw err;
       //now class.scores.studentId becomes ObjectStudent
       //hence you have all scores for all students
});

添加/更新/删除特定学生的分数,针对特定科目(更新或删除时,检索 score[n].performance 数组中的特定元素;添加时,追加到同一个数组.

Class.findOneAndUpdate({name: 'Grade 5 - Section A'
                        ,'scores.studentId': ObjectId('5776bd36ffc8227405d364d2')
                        , 'scores.performance.subjectId' : ObjectId('577694ecbf6f3a781759c54a')}
                        , {$set: {scores.performance. score: 50}}
                        , function(err, data) {
           if (err) throw err
    });

希望对你有帮助