2016-01-22 30 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