Skip to content

Instantly share code, notes, and snippets.

@gatesvp
Created May 2, 2011 20:02
Show Gist options
  • Save gatesvp/952248 to your computer and use it in GitHub Desktop.
Save gatesvp/952248 to your computer and use it in GitHub Desktop.
Pivot Actor/Movies into Movie/Actors
db.foo.drop();
db.foo.insert( { actor: "Richard Gere", movies: ['Pretty Woman', 'Runaway Bride', 'Chicago'] })
db.foo.insert( { actor: "Julia Roberts", movies: ['Pretty Woman', 'Runaway Bride', 'Erin Brockovich'] })
map = function() {
for(var i in this.movies){
key = { movie: this.movies[i] };
value = { actors: [ this.actor ] };
emit(key, value);
}
}
reduce = function(key, values) {
actor_list = { actors: [] };
for(var i in values) {
actor_list.actors = values[i].actors.concat(actor_list.actors);
}
return actor_list;
}
printjson(db.foo.mapReduce(map, reduce, "pivot"));
db.pivot.find().forEach(printjson);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment