在MongoDB中查找数组内的字段总和 [英] Find sum of fields inside array in MongoDB

查看:193
本文介绍了在MongoDB中查找数组内的字段总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据如下:

> db.PQRCorp.find().pretty()
{
    "_id" : 0,
    "name" : "Ancy",
    "results" : [
            {
                    "evaluation" : "term1",
                    "score" : 1.463179736705023
            },
            {
                    "evaluation" : "term2",
                    "score" : 11.78273309957772
            },
            {
                    "evaluation" : "term3",
                    "score" : 6.676176060654615
            }
    ]
}
{
    "_id" : 1,
    "name" : "Mark",
    "results" : [
            {
                    "evaluation" : "term1",
                    "score" : 5.89772766299929
            },
            {
                    "evaluation" : "term2",
                    "score" : 12.7726680028769
            },
            {
                    "evaluation" : "term3",
                    "score" : 2.78092882672992
            }
    ]
}
{
    "_id" : 2,
    "name" : "Jeff",
    "results" : [
            {
                    "evaluation" : "term1",
                    "score" : 36.78917882992872
            },
            {
                    "evaluation" : "term2",
                    "score" : 2.883687879200287
            },
            {
                    "evaluation" : "term3",
                    "score" : 9.882668212003763
            }
    ]
}

我要实现的目标是:: 查找在合计(term1 + term2 + term3)中失败的员工

What I want to achieve is ::Find employees who failed in aggregate (term1 + term2 + term3)

我正在做并最终得到的是:

What I am doing and eventually getting is:

db.PQRCorp.aggregate([ 
{$unwind:"$results"},
{ $group: {_id: "$id",
   'totalTermScore':{ $sum:"$results.score" }
  }
}])

输出: {"_id":null,"totalTermScore":90.92894831067625} 简而言之,我得到的是所有分数的固定总和. 我想要的是,分别为单独的员工合计1、2和3.

OUTPUT:{ "_id" : null, "totalTermScore" : 90.92894831067625 } Simply I am getting a output of a flat sum of all scores. What I want is, to sum terms 1 , 2 and 3 separately for separate employees.

请有人可以帮助我.我是MongoDB的新手(虽然很明显).

Please can someone help me. I am new to MongoDB (quite evident though).

推荐答案

您无需在此处使用$unwind$group ...一个简单的$project查询可以$sum您的整个分数...

You do not need to use $unwind and $group here... A simple $project query can $sum your entire score...

db.PQRCorp.aggregate([
  { "$project": {
    "name": 1,
    "totalTermScore": {
      "$sum": "$results.score"
    }
  }}
])

这篇关于在MongoDB中查找数组内的字段总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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