public
anonymous / example2.js
Last active

MongoDB map reduce example 2

  • Download Gist
example2.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// suggested shell cmd line to run this:
//
// mongo --shell example2.js
//
// Note: the { out : … } parameter is for mongodb 1.8+
 
db.things.insert( { _id : 1, tags : ['dog', 'cat'] } );
db.things.insert( { _id : 2, tags : ['cat'] } );
db.things.insert( { _id : 3, tags : ['mouse', 'cat', 'dog'] } );
db.things.insert( { _id : 4, tags : [] } );
 
// map function
m = function(){
this.tags.forEach(
function(z){
emit( z , { count : 1 } );
}
);
};
 
// reduce function
r = function( key , values ){
var total = 0;
for ( var i=0; i<values.length; i++ )
total += values[i].count;
return { count : total };
};
 
res = db.things.mapReduce(m, r, { out : "myoutput" } );
 
printjson(res);
 
print("try db.myoutput.find()");

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.