I was just testing out the new aggregation framework that is coming in 2.1.0 and thought that I would share how to group by the date.
Example Document:
{
"OriginationDate" : ISODate("2006-12-12T08:00:00Z"),
"AmountBorrowed" : 2250.40
}
Originally I had just grouped by the OriginationDate, but that was grouping by the full datetime:
db.runCommand({
aggregate: 'Loan',
pipeline: [
{
$group: {
_id: "$OriginationDate",
TotalBorrowed: { $sum: "$AmountBorrowed" }
}
}
]
});
Resulting in:
{
"_id" : ISODate("2006-06-23T07:00:00Z"),
"AmountBorrowed" : 174552
}
I used the $year, $month, and $dayOfMonth
expressions to make the _id be unique by day:
db.runCommand({
aggregate: 'Loan',
pipeline: [
{
$group: {
_id: {
OriginationYear: { $year: "$OriginationDate" },
OriginationMonth: { $month: "$OriginationDate" },
OriginationDay: { $dayOfMonth: "$OriginationDate" }
},
TotalBorrowed: { $sum: "$AmountBorrowed" }
}
}
]
});
Using the expressions I get 'an order-preserving concatenated key' that is unique by day, not by the full datetime:
{
"_id" : {
"OriginationYear" : 2009,
"OriginationMonth" : 12,
"OriginationDay" : 31
},
"AmountBorrowed" : 408503
}
The aggregation framework is looking to be pretty awesome!