Skip to content

Instantly share code, notes, and snippets.

@loopj
Created October 4, 2011 23:19
Show Gist options
  • Save loopj/1263135 to your computer and use it in GitHub Desktop.
Save loopj/1263135 to your computer and use it in GitHub Desktop.
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