国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > MongoDB > 正文

MongoDB學習筆記之分組(group)使用示例

2020-03-14 13:20:09
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了MongoDB學習筆記之分組(group)使用示例,本文直接給出一組測試數據,然后練習分組的基本使用,需要的朋友可以參考下

 

 
  1. // 準備測試數據 
  2. db.user.drop(); 
  3. for(var i=10; i< 100; i++) { 
  4. db.user.insert({ 
  5. name:"user" + i,  
  6. age : Math.floor(Math.random()*10)+ 20,  
  7. sex : Math.floor(Math.random()*3)%2 ==0 ? 'M' : 'F'
  8. chinese : Math.floor(Math.random()*50)+50, 
  9. math : Math.floor(Math.random()*50)+50, 
  10. english : Math.floor(Math.random()*50)+50, 
  11. class : "C" + i%5 
  12. }) 
  13.  
  14. // group函數 
  15. // 按照class進行分組,顯示每個class中的用戶姓名和性別 
  16. db.user.group({ 
  17. key: {"class"true}, 
  18. initial: {"person": []}, 
  19. reduce: function(cur, prev) { 
  20. prev.person.push({name: cur.name, sex: cur.sex, age: cur.age}); 
  21. }); 
  22.  
  23. // 對age>25的用戶,按照class進行分組,顯示每個class中的用戶姓名和性別,并統計每組的人數 
  24. db.user.group({ 
  25. key: {"class"true}, 
  26. initial: {"person": []}, 
  27. reduce: function(doc, out){ 
  28. out.person.push({name: doc.name, sex: doc.sex, age: doc.age}); 
  29. }, 
  30. finalize: function(out){ 
  31. out.count = out.person.length; 
  32. }, 
  33. condition: {"age": {$gt: 25}} 
  34. }) 
  35.  
  36. // 分組計算每個class中,chinese最大值和最小值 
  37. db.user.group({ 
  38. key: {"class"true}, 
  39. initial: {"chinese_min": 0, "chinese_max":0 }, 
  40. reduce: function(doc, out){ 
  41. out.chinese_min = doc.chinese; 
  42. out.chinese_min = doc.chinese; 
  43.  
  44. out.chinese_min = Math.min(out.chinese_min, doc.chinese); 
  45. out.chinese_max = Math.max(out.chinese_max, doc.chinese) 
  46. }, 
  47. }) 
  48.  
  49. // 利用分組,計算每個總成績和成績平均值 
  50. db.user.group({ 
  51. key: {"_id" : true}, 
  52. initial: {name:"", total: 0, avg: 0}, 
  53. reduce: function(doc, out){ 
  54. out.name = doc.name; 
  55. out.total = doc.chinese + doc.math + doc.english; 
  56. out.avg = Math.floor(out.total / 3); 
  57. }) 

group參數選項:

1.key: 這個就是分組的key

2.initial: 每組都分享一個初始化函數,特別注意:是每一組initial函數。

3.reduce: 這個函數的第一個參數是當前的文檔對象,第二個參數是上一次function操作的累計對象。有多少個文檔, $reduce就會調用多少次。

4.condition: 這個就是過濾條件。

5.finalize: 這是個函數,每一組文檔執行完后,多會觸發此方法。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 仲巴县| 五台县| 林芝县| 白沙| 阿城市| 兴山县| 屏东县| 礼泉县| 湖南省| 临沂市| 秦安县| 广饶县| 焦作市| 丹江口市| 文山县| 昭觉县| 德钦县| 平顺县| 岳普湖县| 湟源县| 黎平县| 泸定县| 铜山县| 彰化县| 龙门县| 灵武市| 丰顺县| 福安市| 霞浦县| 揭阳市| 左云县| 修水县| 巴东县| 凌海市| 宁远县| 茌平县| 蕉岭县| 大竹县| 保定市| 鸡泽县| 宿迁市|