如何聚合mongoDB中所有科目的分数

编程入门 行业动态 更新时间:2024-10-14 04:28:00
本文介绍了如何聚合mongoDB中所有科目的分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下数据的集合

{ "_id": "SG01", "name": "Pawan", "marks": [ { "English": 93, "Maths": 90, "Hindi": 89, "Sci": 98 } ], "__v": 0 } { "_id": "SG02", "name": "Dravid", "marks": [ { "English": 40, "Maths": 67, "Hindi": 56, "Sci": 45 } ], "__v": 0 } { "_id": "SG03", "name": "Kartik", "marks": [ { "English": 65, "Maths": 77, "Hindi": 80, "Sci": 79 } ], "__v": 0 }

我想执行将marks 显示为特定学生的total_marks 的操作.因为我是 mongo 的新手并且知道如何使用 sum 执行基本聚合但无法理解数组..但是我尝试过但未能得到结果.

I would like to perform the operation in which marks should be displayed as total_marks of a particular student. As I'm newbie with mongo and know how to perform basic aggregation with sum but wasn't able to understand with arrays.. However I tried but failed to get the result.

推荐答案

您可以使用以下聚合:

db.col.aggregate([ { $unwind: "$marks" }, { $project: { _id: 1, name: 1, marks: { $objectToArray: "$marks" } } }, { $project: { _id :1, name: 1, total_marks: { $reduce: { input: "$marks", initialValue: 0, in: { $add : ["$$value", "$$this.v"] } } } } }, { $group: { _id: "$_id", name: { $first: "$name" }, total_marks: { $sum: "$total_marks" } } } ])

由于您的标记存储为对象,您应该使用 $objectToArray 获取一组主题.然后你可以使用 $reduce 来总结一个学生的所有科目.

Since your marks are stored as an object you should use $objectToArray to get an array of subjects. Then you can use $reduce to sum all subjects for one student.

更多推荐

如何聚合mongoDB中所有科目的分数

本文发布于:2023-11-22 14:33:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:科目   分数   mongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!