Created
October 4, 2011 23:19
-
-
Save loopj/1263135 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MongoHelpers | |
# Sum over fields | |
def self.sum(collection, fields, group_by, conditions=nil) | |
map = <<-EOD | |
function() { | |
self = this; | |
key = {}; | |
if(group_by && group_by.length > 0) { | |
group_by.forEach(function (g) { | |
key[g] = self[g]; | |
}); | |
} else { | |
key["group"] = true; | |
} | |
vals = {}; | |
fields.forEach(function (f) { | |
vals[f] = self[f]; | |
}) | |
emit(key, vals) | |
} | |
EOD | |
reduce = <<-EOD | |
function (key, values) { | |
totals = {}; | |
values.forEach(function (v) { | |
fields.forEach(function (f) { | |
if(v[f]) { | |
if(totals[f]) { | |
if(typeof(v[f]) == "object" && typeof(v[f].concat) == "function") { | |
totals[f] = totals[f].concat(v[f]); | |
} else { | |
totals[f] += v[f]; | |
} | |
} else { | |
totals[f] = v[f]; | |
} | |
} | |
}); | |
}); | |
return totals; | |
} | |
EOD | |
MongoUtil.connection[collection].map_reduce(map, reduce, { | |
:query => conditions, | |
:scope => { | |
"group_by" => group_by, | |
"fields" => fields | |
}, | |
:out => 'inline' | |
}).find | |
end | |
# Helper function for renaming a field in all documents in a collection | |
def self.rename_field(collection, old_name, new_name) | |
func = <<-EOD | |
function rename_field(collection, old_name, new_name) { | |
criteria = {} | |
criteria[old_name] = { $exists: true } | |
old_field = {} | |
old_field[old_name] = true | |
db[collection].find(criteria, old_field).forEach(function (doc) { | |
new_field = {} | |
new_field[new_name] = doc[old_name] | |
db[collection].update({_id: ObjectId(doc._id)}, { | |
$set: new_field, | |
$unset: old_field | |
}); | |
}); | |
} | |
EOD | |
MongoUtil.connection.eval(func, collection, old_name, new_name) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment