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

首頁 > 數據庫 > MongoDB > 正文

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

2020-10-29 18:50:43
字體:
來源:轉載
供稿:網友
// 準備測試數據db.user.drop();for(var i=10; i< 100; i++) {  db.user.insert({    name:"user" + i,     age : Math.floor(Math.random()*10)+ 20,     sex : Math.floor(Math.random()*3)%2 ==0 ? 'M' : 'F',    chinese : Math.floor(Math.random()*50)+50,    math : Math.floor(Math.random()*50)+50,    english : Math.floor(Math.random()*50)+50,    class : "C" + i%5  })}// group函數// 按照class進行分組,顯示每個class中的用戶姓名和性別db.user.group({  key: {"class": true},  initial: {"person": []},  reduce: function(cur, prev) {    prev.person.push({name: cur.name, sex: cur.sex, age: cur.age});  }});// 對age>25的用戶,按照class進行分組,顯示每個class中的用戶姓名和性別,并統計每組的人數db.user.group({  key: {"class": true},  initial: {"person": []},  reduce: function(doc, out){    out.person.push({name: doc.name, sex: doc.sex, age: doc.age});  },  finalize: function(out){    out.count = out.person.length;  },  condition: {"age": {$gt: 25}}})// 分組計算每個class中,chinese最大值和最小值db.user.group({  key: {"class": true},  initial: {"chinese_min": 0, "chinese_max":0 },  reduce: function(doc, out){    out.chinese_min = doc.chinese;    out.chinese_min = doc.chinese;    out.chinese_min = Math.min(out.chinese_min, doc.chinese);    out.chinese_max = Math.max(out.chinese_max, doc.chinese)  },})// 利用分組,計算每個總成績和成績平均值db.user.group({  key: {"_id" : true},  initial: {name:"", total: 0, avg: 0},  reduce: function(doc, out){    out.name = doc.name;    out.total = doc.chinese + doc.math + doc.english;    out.avg = Math.floor(out.total / 3);  }})

group參數選項:

1.key: 這個就是分組的key
2.initial: 每組都分享一個初始化函數,特別注意:是每一組initial函數。
3.reduce: 這個函數的第一個參數是當前的文檔對象,第二個參數是上一次function操作的累計對象。有多少個文檔, $reduce就會調用多少次。
4.condition: 這個就是過濾條件。
5.finalize: 這是個函數,每一組文檔執行完后,多會觸發此方法。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新泰市| 廉江市| 通渭县| 南郑县| 绥滨县| 义乌市| 稷山县| 夏河县| 浮梁县| 明溪县| 阳原县| 毕节市| 当涂县| 礼泉县| 宿松县| 灵川县| 台湾省| 维西| 南投市| 广德县| 中牟县| 芒康县| 嘉义县| 宁明县| 清河县| 澄城县| 罗甸县| 福泉市| 阿拉善左旗| 柳林县| 久治县| 西峡县| 井陉县| 仪陇县| 彩票| 长顺县| 应城市| 田阳县| 芦山县| 天等县| 中方县|