Skip to content

Instantly share code, notes, and snippets.

@robcowie
Created May 4, 2010 15:18
Show Gist options
  • Save robcowie/389539 to your computer and use it in GitHub Desktop.
Save robcowie/389539 to your computer and use it in GitHub Desktop.
mongodb map-reduce to group by week
m = function() {
var getWeek = function(d) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */
dowOffset = 1;
var newYear = new Date(d.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset;
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((d.getTime() - newYear.getTime() - (d.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
if (day < 4) {
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52) {
nYear = new Date(d.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
weeknum = nday < 4 ? 1 : 53;
}
} else {
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
};
var data = {};
data[this.metadata.serviceref] = 1;
emit(getWeek(this.metadata.publishdate), data);
};
r = function(key, values){
var by_service = {};
values.forEach(function(service_counts){
// Add {cg:1, gp:1} to {cg:11, gp:22}
for (serviceref in service_counts) {
var count = service_counts[serviceref];
by_service[serviceref] = by_service[serviceref] || 0;
by_service[serviceref] += count;
};
});
return by_service;
};
// USAGE
use publications
res = db.reports.files.mapReduce(m, r, {
query: {'metadata.publishdate': {$gte: new Date(2009, 03, 04), $lte:new Date(2010, 03, 04)}}
})
db[res.result].find()
@febielgiva
Copy link

can you please provide a input json and output json??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment