如何聚合mongoDB中所有科目的分数 [英] How to aggregate the marks of all the subjects in mongoDB

查看:47
本文介绍了如何聚合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中所有科目的分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆