Prepare test data db.user.drop ();
for (var i=10 i< 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.F Loor (Math.random () *50) +50, class: "C" + i%5})}//Group function//Group by class, displaying the user name and gender Db.user.group in each class ({Ke Y: {"class": true}, initial: {"person": []}, Reduce:function (cur, prev) {Prev.person.push ({name:cur.name, sex:
Cur.sex, age:cur.age});
}
}); For age>25 users, group by class, showing the name and sex of the user in each class, and counting the number of people in each group 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}}})//group Chinese Maximum and minimum 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)}//Use grouping to calculate each total score and achievement average Db.user.group ({key: {"_id": TR
UE}, 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 parameter options:
1.key: This is the key of the group
2.initial: Each group shares an initialization function, with particular attention: each group of initial functions.
3.reduce: The first parameter of this function is the current document object, and the second is the cumulative object of the last function operation. How many documents $reduce will be called.
4.condition: This is the filtration condition.
5.finalize: This is a function that will trigger this method more than once after each set of documents has finished executing.