public
Last active

  • Download Gist
callingTheStoredFunction.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
db.system.js.findOne({_id: 'assetSizeBuckets'}).value(); // returns the following
[
{
"medium" : true,
"tsize" : 4186349249,
"count" : 114905,
"avg_size" : 36433.13388451329
},
{
"short" : true,
"tsize" : 248746572,
"count" : 45364,
"avg_size" : 5483.347412044794
},
{
"large" : true,
"tsize" : 25573745030,
"count" : 41777,
"avg_size" : 612148.9104052469
}
]
calling_the_stored_function.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14
db = Mongo::Connection.new.db('assets')
db.eval('assetSizeBuckets()')
 
##############################
#
# returns:
#
# [
# {"medium"=>true, "tsize"=>4186349249.0, "count"=>114905.0, "avg_size"=>36433.1338845133},
# {"short"=>true, "tsize"=>248746572.0, "count"=>45364.0, "avg_size"=>5483.34741204479},
# {"large"=>true, "tsize"=>25573745030.0, "count"=>41777.0, "avg_size"=>612148.910405247}
# ]
#
##############################
storedFunction.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// A simple grouping of Assets that mirror GridFS documents
db.system.js.save(
{ _id: 'assetSizeBuckets',
value: function() {
return db.assets.group({
keyf: function(asset) {
if(asset.file_size < 10000) {
return {small: true}
} else if(asset.file_size < 100000) {
return {medium: true}
} else {
return {large: true}
}
},
initial: {tsize: 0.0, count: 0},
reduce: function(asset,memo){
memo.count++;
memo.tsize += asset.file_size;
},
finalize: function(out){ out.avg_size = out.tsize / out.count }
});
}
}
);
 
// Where an Asset is a document like this:
{
"_id" : ObjectId("4be2f7ac80faa9d88e000005"),
"file_name" : "some_file.html",
"file_size" : 16849,
"file_type" : "text/html",
"file_id" : ObjectId("4be2f7ac80faa9d88e000006")
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.