MongoDB嵌套数组查询、分数统计及$out存储结果问题咨询
MongoDB 解决方案:计算平均分与分数达标检查并存储结果
1. 计算每种测试类型的平均分
使用聚合管道拆分分数数组并按类型分组求平均值:
db.Stumarks.aggregate([ // 拆分scores数组,将每个分数项转为独立文档 { $unwind: "$scores" }, // 按测试类型分组,计算平均分 { $group: { _id: "$scores.type", averageScore: { $avg: "$scores.score" } } } ])
执行后会输出各类型的平均分结果,示例:
{ "_id" : "exam", "averageScore" : 84.37799696030743 } { "_id" : "quiz", "averageScore" : 15.95792143439528 } { "_id" : "homework", "averageScore" : 77.80745176713172 }
2. 检查分数达标并存储结果到集合
find 命令不支持 $out 阶段,必须改用聚合管道实现查询结果的存储。以下提供两种场景的解决方案:
场景一:按类型分别存储达标文档
将每个类型中分数≥40的文档单独存入对应集合:
// 存储exam分数达标文档到exam_passing集合 db.Stumarks.aggregate([ { $match: { "scores": { $elemMatch: { type: "exam", score: { $gte: 40 } } } } }, { $out: "exam_passing" } ]) // 存储quiz分数达标文档到quiz_passing集合 db.Stumarks.aggregate([ { $match: { "scores": { $elemMatch: { type: "quiz", score: { $gte: 40 } } } } }, { $out: "quiz_passing" } ]) // 存储homework分数达标文档到homework_passing集合 db.Stumarks.aggregate([ { $match: { "scores": { $elemMatch: { type: "homework", score: { $gte: 40 } } } } }, { $out: "homework_passing" } ])
场景二:生成包含各类型达标状态的统一集合
为每个学生生成标记各类型是否达标的文档,并存入集合:
db.Stumarks.aggregate([ { $unwind: "$scores" }, { $group: { _id: "$_id", name: { $first: "$name" }, examPass: { $max: { $cond: [{ $gte: ["$scores.score", 40] }, { $eq: ["$scores.type", "exam"] }, false] } }, quizPass: { $max: { $cond: [{ $gte: ["$scores.score", 40] }, { $eq: ["$scores.type", "quiz"] }, false] } }, homeworkPass: { $max: { $cond: [{ $gte: ["$scores.score", 40] }, { $eq: ["$scores.type", "homework"] }, false] } } } }, { $out: "student_score_status" } ])
执行后,student_score_status 集合中的文档会包含 examPass、quizPass、homeworkPass 三个布尔字段,标记对应类型是否有分数≥40。
内容的提问来源于stack exchange,提问作者Venkatesh Kumar
相关产品推荐
相关产品推荐

