Skip to content

Instantly share code, notes, and snippets.

@vbernabe
Created June 19, 2014 04:46
Show Gist options
  • Save vbernabe/627d4fc8d6377d3fe50e to your computer and use it in GitHub Desktop.
Save vbernabe/627d4fc8d6377d3fe50e to your computer and use it in GitHub Desktop.
MongoDB: Count item created per year month using ObjectId as timestamp (map - reduce)
db.accounts.mapReduce(
// Map function. Convert object id to timestamp then extract year-month
function(){
var ac_create_date = this._id.getTimestamp();
var year = ac_create_date.getFullYear();
var month = ac_create_date.getMonth()+1;
emit(year+"-"+month, 1);
},
// Reduce function. Just sum up the values from map.
function(key, value){
return Array.sum(value);
},
{
out: "mapred_account_created_per_month", // output result to this collection
query: { _id: { $gt: ObjectId("555a0c800000000000000000") } // optional: you can remove this. Just addtl condition to query dates greater than object which is just a timestamp converted to object
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment