2017-09-27 50 views
0

我有一個在數學,寫作和閱讀等級的學生的mongo集合。我需要總結所有的數學,寫作和閱讀成績。如何在MongoDB中彙總一個集合中的所有值

例如,如果三年級的學生在數學各得到50則總和是150

到目前爲止,我有:

db.student.aggregate([{$組:{ 「_ ID」: null,總數:{$ sum:「$ math score」}}}])

我一直在Google上搜尋一個小時左右。我沒有使用mongo的經驗,所以它一直很慢。

這裏是我的數據樣本

{ 
"student_data": 
[ 
    { 
    "S-ID": 91371, 
    "gender": "male", 
    "race/ethnicity": "group B", 
    "parental level of education": "some college", 
    "lunch": "standard", 
    "test preparation course": "completed", 
    "math score": 44, 
    "reading score": 50, 
    "writing score": 48, 
    "Total Score": 142 
}, 
+1

你能提供一個樣本數據庫數據,以便我可以瞭解如何存儲數據 – Vignesh

+0

我已經添加了一些示例數據,我認爲我越來越亂了,因爲數據在數組內。 – Hunter

+0

我已經添加了一個答案,請檢查它@hunter – Vignesh

回答

0

試試這個關於大小:

db = db.getSiblingDB("testX"); 

function show(c,emit=true) { 
    var nn = 0; 
    c.forEach(function(r) { 
     nn++; 
     if(emit == true) { 
      printjson(r); 
     } 
    }); 
print("found " + nn); 
}; 

db.foo.drop(); // CAREFUL! This drops "foo" every time! 

var students = [ 
      {_id:1, studentId:"A1", math:10, writing:15, reading: 17} 
      ,{_id:2, studentId:"A2", math:12, writing:17, reading: 19} 
      ,{_id:3, studentId:"A3", math:14, writing:19, reading: 21} 
      ,{_id:4, studentId:"A4", math:16, writing:21, reading: 23} 
      ]; 

db.foo.insert(students); 

c = db.foo.aggregate([ 
    {$group: {_id: null, totMath: {$sum: "$math"}, totWrite: {$sum: "$writing"}, totRead: {$sum: "$reading"}}} 
        ]); 

show(c, true); 
0

如果您在DB具有這樣的數據如下

 {"student_data":[{ 
     "S-ID": 91371, 
     "gender": "male", 
     "race/ethnicity": "group B", 
     "parental level of education": "some college", 
     "lunch": "standard", 
     "test preparation course": "completed", 
     "math score": 44, 
     "reading score": 50, 
     "writing score": 48, 
     "Total Score": 142 
    },{ 
     "S-ID": 91371, 
     "gender": "male", 
     "race/ethnicity": "group B", 
     "parental level of education": "some college", 
     "lunch": "standard", 
     "test preparation course": "completed", 
     "math score": 44, 
     "reading score": 50, 
     "writing score": 48, 
     "Total Score": 142 
    },{ 
     "S-ID": 91371, 
     "gender": "male", 
     "race/ethnicity": "group B", 
     "parental level of education": "some college", 
     "lunch": "standard", 
     "test preparation course": "completed", 
     "math score": 44, 
     "reading score": 50, 
     "writing score": 48, 
     "Total Score": 142 
    }] 



    db.collection.aggregate([ 
    {$unwind:'student_data'}, 
    {$group: 
    {_id:'null', 
    {count:{$sum:$math score} 
    }} 
    }]) 
+0

當我運行命令時,我得到一個錯誤[thread1] SyntaxError:無效的屬性id @(shell):5:4。我也確保將收藏品更改爲實際收藏品名稱。 – Hunter

+0

我試圖在Python中使用相同的命令,並收到[{'_id':None,'total':0}] – Hunter

+0

我想到了,我需要在組中添加$ student_data.math分數。謝謝您的幫助。 – Hunter

相關問題