Skip to content

Instantly share code, notes, and snippets.

@carlossanchezp
Last active December 22, 2015 20:49
Show Gist options
  • Select an option

  • Save carlossanchezp/6529615 to your computer and use it in GitHub Desktop.

Select an option

Save carlossanchezp/6529615 to your computer and use it in GitHub Desktop.
MongoDB shell
> db.things.insert( { _id : 1, tags : ['tag1', 'tag2'] } );
> db.things.insert( { _id : 2, tags : ['tag2'] } );
> db.things.insert( { _id : 3, tags : ['tag1', 'tag2', 'tag3'] } );
> db.things.insert( { _id : 4, tags : [] } );
> // función de mapeo
> m = function(){
... this.tags.forEach(
... function(z){
... emit( z , { count : 1 } );
... }
... );
...};
> // función reductora
> 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" } );
> res
{
"result" : "myoutput",
"timeMillis" : 12,
"counts" : {
"input" : 4,
"emit" : 6,
"output" : 3
},
"ok" : 1,
}
> db.myoutput.find()
{"_id" : "tag1" , "value" : {"count" : 3}}
{"_id" : "tag2" , "value" : {"count" : 2}}
{"_id" : "tag3" , "value" : {"count" : 1}}
> db.myoutput.drop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment