Skip to content

Instantly share code, notes, and snippets.

@buger
Last active December 18, 2015 09:59
Show Gist options
  • Save buger/5765417 to your computer and use it in GitHub Desktop.
Save buger/5765417 to your computer and use it in GitHub Desktop.
Mongodb reduce function for complex object
// Universal mongodb reduce function for complex objects
//
// Example:
//
// emit({ total_views: 3, page_type: {home: 1, product: 2}, site_id: [1] })
// emit({total_views: 5, page_type: {home: 1, collection: 4}, site_id: [2]})
//
// -> reduce
//
// { total_views: 8, page_type: { home: 2, product: 2, collection: 4 }, site_id: [1,2] }
//
function(key, values){
var result = {}
var merge_obj = function(from, to){
for (key in from) {
if (Object.prototype.toString.call(from[key]) == "[object Object]") {
if (!to[key])
to[key] = {}
merge_hash(from[key], to[key])
} else if (Object.prototype.toString.call(from[key]) == "[object Array]") {
if (!to[key])
to[key] = []
to[key].push(from[key])
} else {
if (!to[key])
to[key] = 0
to[key] += from[key]
}
}
}
values.forEach(function(value){
merge_obj(value, result)
})
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment