MongoDB's mapreduce mainly consists of two methods: Map and reduce.
For example, let's say we have the following 3 records
{"_id": ObjectId ("4e5ff893c0277826074ec533"), "X": ["a", "B""_id": ObjectId ("4e5ff893c0277826074ec534"), "X ": [" B "," C "" _id ": ObjectId (" 4e5ff893c0277826074ec535 ")," X ": [" C "," D "]}
The map method calls the emit method, returns the value of the key value pair, the key is x[i], such as A; The value is 1.
function () { for (var0this. x.length; i++) { emit ( This 1 ); }}
The reduce method is responsible for the statistics of key-value pairs.
function (key, values) { var0; for (var0; i < values.length; i++) + = Values[i] ; return sum;}
Execution results are as follows
{"_id":"a","value":1 }{ "_id":"b","value":2 }{ "_id":"C","value":2 }{ "_id":"D","value":1}
Assuming that the map and reduce methods are stored in Map.js and Reduce.js, the MapReduce results can be obtained from the following code.
mapreduceresults<valueobject> results = mongooperations.mapreduce ("Jmr1", "Classpath:map.js", "Classpath: Reduce.js ", Valueobject. class ); for (Valueobject valueobject:results) { System.out.println (valueobject);}
Output is
Valueobject [ID=a, value=1.0]valueobject [ID=b, value=2.0] Valueobject [ID=c, value=2.0]valueobject [ID=d, value=1.0]
Valueobject Code
Public classValueobject {PrivateString ID; Private floatvalue; PublicString getId () {returnID; } Public floatGetValue () {returnvalue; } Public voidSetValue (floatvalue) { This. Value =value; } @Override PublicString toString () {return"Valueobject [id=" + ID + ", value=" + value + "]"; }}
You can add a mapreduceoptions to add some map-reduce options, and the results are stored in collection.
mapreduceresults<valueobject> results = mongooperations.mapreduce ("Jmr1", "Classpath:map.js", "Classpath: Reduce.js ", new mapreduceoptions (). OutputCollection (" Jmr1_out "), Valueobject. Class);
Mapreduceoptions can also be instantiated by means of the static method options ().
mapreduceresults<valueobject> results = mongooperations.mapreduce ("Jmr1", "Classpath:map.js", "Classpath: Reduce.js ", Options (). OutputCollection (" Jmr1_out "), Valueobject. Class);
You can also add a query to filter the statistics, which excludes the document containing A and B.
New Query (WHERE ("X"). NE (new string[] {"A", "B" }); Mapreduceresults<ValueObject> results = mongooperations.mapreduce (query, "JMR1", "Classpath:map.js", " Classpath:reduce.js ", Options (). OutputCollection (" Jmr1_out "), Valueobject. Class);