Mongo aggregation framework: group users by age
mongodb
Solution
It seems like the whole thing is possible with the new Mongo 2.4 version just released, supporting additional Date operations (namely the "$subtract").
Here's how I did it:
db.Users.aggregate([
{ $match : { "DateOfBirth" : { $exists : true} } },
{ $project : {"ageInMillis" : {$subtract : [new Date(), "$DateOfBirth"] } } },
{ $project : {"age" : {$divide : ["$ageInMillis", 31558464000] }}},
// take the floor of the previous number:
{ $project : {"age" : {$subtract : ["$age", {$mod : ["$age",1]}]}}},
{ $group : { _id : "$age", Total : { $sum : 1} } },
{ $sort : { "Total" : -1 } }
])
Problem
I have a user base stored in mongo. Users may record their date of birth. I need to run a report aggregating users by age. I now have a pipeline that groups users by year of birth. However, that is not precise enough because most people are not born on January 1st; so even if they are born in, say, 1970, they may well not be 43 yet. ``` db.Users.aggregate([ { $match : { "DateOfBirth" : { $exists : true} } }, { $project : {"YearOfBirth" : {$year : "$DateOfBirth"} } }, { $group : { _id : "$YearOfBirth", Total : { $sum : 1} } }, { $sort : { "Total" : -1 } } ]) ``` Do you know if it's possible to perform some kind of arithmetic within the aggregation framework to exactly calculate the age of a user? Or is this possible with MapReduce only?