Skip to content

Instantly share code, notes, and snippets.

@sebastianvoss
Last active December 20, 2015 13:39
Show Gist options
  • Save sebastianvoss/6140668 to your computer and use it in GitHub Desktop.
Save sebastianvoss/6140668 to your computer and use it in GitHub Desktop.
MongoDB Shell MapReduce sample
// map function
m = function () {
this.images.forEach( function(id) {
emit(id, 1);
})
}
// reduce function
r = function (id, count) {
return Array.sum(count);
}
// create a image count in collection map_reduce_sample
db.albums.mapReduce(m, r, {out: "map_reduce_sample"})
// tag all images which are in use
db.map_reduce_sample.find().forEach(function(d) {
db.images.update({_id: d._id}, {$set: {in_use: true}})
})
// remove unused images
db.images.remove({in_use: {$exists: false}})
// remove in_use tag
db.images.update({}, {$unset: {in_use: ""}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment