Skip to content

Instantly share code, notes, and snippets.

@Loksly
Created November 4, 2016 18:46
Show Gist options
  • Save Loksly/0df64edd9370c300d94747d49225068a to your computer and use it in GitHub Desktop.
Save Loksly/0df64edd9370c300d94747d49225068a to your computer and use it in GitHub Desktop.
Join using two map reduces for stackoverflow ( https://github.com/dsevilla/bdge/blob/master/mongo/sesion4.ipynb )
db.comments.mapReduce(
function(){
emit(this.PostId, { Comments: [ this ]})
},
function(key, val){
var first = val.shift();
var comments = val.reduce(function(valorAnterior, valorActual){
return Array.prototype.concat.apply( valorAnterior, valorActual.Comments);
}, first.Comments );
return {
Comments: comments
};
},
{
out: "post_comments"
}
);
db.posts.mapReduce(
function(){
emit(this.Id, this );
},
function(key, val){
return val.reduce(function(valorAnterior, valorActual){
for (var attr in valorActual){
if (typeof valorAnterior[attr] === 'undefined'){
valorAnterior[attr] = valorActual[attr];
} else if (Array.isArray(valorAnterior[attr])){
valorAnterior[attr].push( valorActual[attr] );
} else {
valorAnterior[attr] = [ valorAnterior[attr], valorActual[ attr] ];
}
}
return valorAnterior;
}, {});
},
{
out: {reduce: 'post_comments'}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment