The following example shows a mapreduce example of mongoose, referring to the Mongoose official website.
Basic concepts:
map Functionaccepts a key-value pair (Key-value pair), which produces a set of intermediate key-value pairs. The MapReduce framework passes the same value of the middle key value generated by the map function to a reduce function.
Reduce functionaccepts a key, together with a related set of values, that merges the set of values to produce a smaller set of values (usually with only one or 0 values).
var user new Schema ({ username:{type:string}, password:{type:string},} )
Exports.test =function(){ varuser = require ('.. /dao/user '); varModel =User.model; varoption = {}; //output is _id:name, value:1Option.map =function() {Emit ( This. Username, 1) } //Pass the same key value to the same reduce function, where k is _id:name and Vals is an array of value //when there are no more than one key-value pair, the reduce function is not calledOption.reduce =function(k, vals) {returnvals.length} model.mapreduce (O,function(err, results) {Console.log (results)});}
// There are three records in the database, a user name is Hello, and two user name is Test [{_id: ' Hello ', value:1}, {_id: ' Test ', value:2}]
MongoDB (Map-reduce)