Skip to content

Instantly share code, notes, and snippets.

@Hasstrup
Last active March 10, 2019 22:41
Show Gist options
  • Save Hasstrup/9be1cced77f0298a219de683e1482320 to your computer and use it in GitHub Desktop.
Save Hasstrup/9be1cced77f0298a219de683e1482320 to your computer and use it in GitHub Desktop.
// we can use this as an example in video 3
const mapFunction = () => {
// this function will be called with the context of
// this locked to the record in iteration
emit(this.user_name, this.price)
}
// Video 3
const reduceFunction = (key, values) => {
return values.reduce((a, b) => a + b)
}
const query = {}
// this doesn't returnn the actual data from the database, some information
// about the operation including the number of hits, the name of the result
//{
// "result" : "products_total",
// "timeMillis" : 9,
// "counts" : {
// "input" : 4,
// "emit" : 4,
// "reduce" : 2,
// "output" : 2
// },
// "ok" : 1,
// }
let res = db.products.mapReduce(mapFunction, reduceFunction, { out: "products_total", query })
// this returns
// To get the actual result you'd have to call a res.find() to inspect the results this is because the
// the results of the operation are sent to a collection (the one provided in the out value)
// So this will serve very well as an example for writing to a collection.
/*
receiving the results inline is also fairly straightforward. You do that by passing an object to the out key. The object
will be something like this { out: { inline: 1 }. so our function will now look like this
*/
res = db
.products
.mapReduce(mapFunction, reduceFunction, { out: { inline: 1 } })
// the results of the operation will be loaded in memory and assigned to the variable res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment