MongoDB學(xué)習(xí)筆記之分組(group)使用示例
// 準(zhǔn)備測(cè)試數(shù)據(jù) 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函數(shù) // 按照class進(jìn)行分組,顯示每個(gè)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}); } }); // 對(duì)age>25的用戶,按照class進(jìn)行分組,顯示每個(gè)class中的用戶姓名和性別,并統(tǒng)計(jì)每組的人數(shù) 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}} }) // 分組計(jì)算每個(gè)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) }, }) // 利用分組,計(jì)算每個(gè)總成績(jī)和成績(jī)平均值 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參數(shù)選項(xiàng):
1.key: 這個(gè)就是分組的key
2.initial: 每組都分享一個(gè)初始化函數(shù),特別注意:是每一組initial函數(shù)。
3.reduce: 這個(gè)函數(shù)的第一個(gè)參數(shù)是當(dāng)前的文檔對(duì)象,第二個(gè)參數(shù)是上一次function操作的累計(jì)對(duì)象。有多少個(gè)文檔, $reduce就會(huì)調(diào)用多少次。
4.condition: 這個(gè)就是過(guò)濾條件。
5.finalize: 這是個(gè)函數(shù),每一組文檔執(zhí)行完后,多會(huì)觸發(fā)此方法。
相關(guān)文章
MongoDB數(shù)據(jù)庫(kù)文檔操作方法(必看篇)
下面小編就為大家?guī)?lái)一篇MongoDB數(shù)據(jù)庫(kù)文檔操作方法(必看篇)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07MongoDB實(shí)現(xiàn)查詢、分頁(yè)和排序操作以及游標(biāo)的使用
本文詳細(xì)講解了MongoDB實(shí)現(xiàn)查詢、分頁(yè)和排序操作以及游標(biāo)的使用方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07MongoDB數(shù)據(jù)庫(kù)的日志文件深入分析
這篇文章主要給大家介紹了關(guān)于MongoDB數(shù)據(jù)庫(kù)日志的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用MongoDB具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09mongodb數(shù)據(jù)庫(kù)入門之CURD簡(jiǎn)單操作示例
這篇文章主要介紹了mongodb數(shù)據(jù)庫(kù)入門之CURD簡(jiǎn)單操作,結(jié)合簡(jiǎn)單示例形式分析了MongoDB數(shù)據(jù)庫(kù)基本的CURD增刪改查相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2019-10-10MongoDB添加仲裁節(jié)點(diǎn)報(bào)錯(cuò):replica set IDs do not match的解決方法
這篇文章主要給大家介紹了關(guān)于MongoDB添加仲裁節(jié)點(diǎn)報(bào)錯(cuò):replica set IDs do not match的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11