Use Map&reduce to calculate the number of students in each class between 10 and 20 years of age in several classes:
- Demand analysis
- Fields for student tables:
Db.students.insert ({classid:1, age:14, Name: ' Tom '})
Will classid Random 1 and 2, age between 8-25 years old randomly, name is randomly between 3-7 characters.
- Data Write
- Data written to Java script
Students write 10 million data to the Mrtask library:
Package org.test; Import Java.util.arraylist;import java.util.list;import Java.util.random;import Com.mongodb.basicdbobject;import Com.mongodb.db;import Com.mongodb.dbcollection;import Com.mongodb.dbcursor;import Com.mongodb.DBObject;import Com.mongodb.mongoclient;import com.mongodb.ServerAddress; public class Testmongodbreplset {public static void main (string[] args) {try {List<serveraddre ss> addresses = new arraylist<serveraddress> (); ServerAddress Address1 = new ServerAddress ("172.16.16.89", 27017); Addresses.add (ADDRESS1); Mongoclient client = new Mongoclient (addresses); DB db = Client.getdb ("Mrtask"); Dbcollection coll = db.getcollection ("Students"); Data is written to basicdbobject object = new Basicdbobject (); for (int i = 1; I <= 10000000; i++) {object.append ("ClassID", 1 + (int) (Math.random () * 2)); Object.append ("Age", 8 + (int) (Math.random () * 17)); Object.append ("Name", GetName ()); Coll.insert (object); Object.clear (); }} catch (Exception e) {e.printstacktrace (); }} public static String GetName () {ArrayList list = new ArrayList (); for (char c = ' a '; c <= ' z '; C + +) {List.add (c); } String str = ""; int end = 3 + (int) (Math.random () * 4); for (int i = 0; i < end; i++) {int num = (int) (Math.random () * 26); str = str + list.get (num); } return str; } }
After viewing, there are 10 million data in the students table in the Mrtask library:
[Email protected] bin]#./mongo
MongoDB Shell version:2.6.11
Connecting To:test
> Show DBS
Admin (empty)
Local 0.078GB
Mrtask 3.952GB
Test 0.453GB
> Use Mrtask
Switched to DB Mrtask
> Db.students.find (). Count ()
10000000
- Map&reduce calculation
- Map calculation
> mapfun = function () {Emit (this.classid,1)}
> reducefun=function (Key, values) {var count = 0; Values.foreach (function (v) {count + = V;}); return count;}
> FF = function (key, value) {return {classid:key, count:value};}
> classid_res = Db.runcommand ({
MapReduce: "Students",
Map:mapfun,
Reduce:reducefun,
Out: "Students_classid_res",
FINALIZE:FF,
query:{age:{$GT: Ten, $lt: 20}}
});
> Db.students_classid_res.find ()
{"_id": 1, "value": {"ClassID": 1, "Count": 2643128}}
{"_id": 2, "value": {"ClassID": 2, "Count": 2650870}}
Remember the MongoDB map&reduce get started operation