2016-01-22 27 views
1

MongoDB的汇总查询我有一个集合,如下所示的总和

{ "_id" : 0, "name" : "aimee Zank", "scores" : 
[ 
    { "type" : "exam", "score" : 1.463179736705023 }, 
    { "type" : "quiz", "score" : 11.78273309957772 }, 
    { "type" : "homework", "score" : 6.676176060654615} 
] } 

{"_id" : 1, "name" : "Aurelia Menendez", "scores" : 
[ 
{ "type" : "exam", "score" : 60.06045071030959 }, 
{ "type" : "quiz", "score" : 52.79790691903873 }, 
{ "type" : "homework", "score" : 71.761334391544 } 
] } 

{"_id" : 2, "name" : "Corliss Zuk", "scores" : 
[ 
{ "type" : "exam", "score" : 67.03077096065002 }, 
{ "type" : "quiz", "score" : 6.301851677835235 }, 
{ "type" : "homework", "score" : 20.18160621941858} 
] } 

现在我想每一个类型的所有分数相应的学生 例如用于学生艾梅赞克我想得分的总和的总和考试+测验+功课。

我已经试过这

db.collection.aggregate(
[ 
    { 
    $group: 
    { 
     _id: "$name", 
     total: { $sum: "$scores.score" }, 
    } 
} 
] 
) 

db.scores.aggregate(
[ 
    { $project: { name: 1, total: { $add: [ "$scores.score" ] } } } 
] 
) 

,但我无法找到一个解决方案 有人可以帮我查询?

+5

我们不会为你做功课。这是MongoDB大学的作业,所以请尝试自己做。 – styvane

+1

这不是一个mongoDB作业,我已经通过该课程,这是一个用例,我正在尝试使用该特定数据集。 –

+3

那么你不会问这个,如果你通过*课程 – styvane

回答

1

发现在计算器没有帮助,只有劝阻组人后,我发现我自己的解决方案,这是我的解决方案只是其中的一部分正在寻找:

db.scores.aggregate(
[ 

{ $unwind : "$scores"}, 
    { $group: 
    { 
     _id: "$name", 
     total: { $sum: "$scores.score" } 
    } 
} 

] 
) 
+2

不要感到气馁...我们没有给你解决方案,因为我们知道你有能力解决这个问题。 :) – dikesh