Skip to content

Instantly share code, notes, and snippets.

@serpent403
Last active December 28, 2015 15:59
Show Gist options
  • Save serpent403/7525940 to your computer and use it in GitHub Desktop.
Save serpent403/7525940 to your computer and use it in GitHub Desktop.
Map Reduce Example
use tutorial
db.orders.insert({ cust_id: "A123", amount: 500, status: "A" })
db.orders.insert({ cust_id: "A123", amount: 250, status: "A" })
db.orders.insert({ cust_id: "B212", amount: 200, status: "A" })
db.orders.insert({ cust_id: "A123", amount: 300, status: "D" })
// Calculate the sum of all “amount”s for a unique “cust_id”
var map = function() {
emit(this.cust_id, this.amount);
}
var reduce = function(keyCustId, values) {
return Array.sum(values);
}
var options = {
query: { status: "A" },
out: "order_totals"
}
db.orders.mapReduce(map, reduce, options)
/*
Output:
> db.order_totals.find()
{ "_id" : "A123", "value" : 750 }
{ "_id" : "B212", "value" : 200 }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment