How to aggregate by date when a full timestamp is given in aggregation framework?
Since mongo 2.6 is there $dateToString function that can be used in aggregate
like that:
db.errors.aggregate([
{
$group : {
_id: { $dateToString: { format: "%Y-%m-%d", date: "$date" }},
count: { $sum: 1 }
}
}
]);
You can do this by using the following aggregation operators:
- $group
- $year
- $month
- $dayOfMonth
This gives you the error count for each date:
db.errors.aggregate(
{ $group : {
_id: {
year : { $year : "$date" },
month : { $month : "$date" },
day : { $dayOfMonth : "$date" },
},
count: { $sum: 1 }
}}
);
This example assumes that the date field in your error documents is date
and of type BSON Date. There is also a Timestamp type in MongoDB, but use of this type is explicitely discouraged by the documentation:
Note: The BSON Timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type. See Date for more information.
You can convert your timestamp field to string with specific date format by using $project (aggregation)
aggregate([
{
'$project': {
newFieldName: {'$dateToString': {format: '%Y-%m-%d', date: '$yourDateFieldName'}}
}
}, {
'$group': {
_id: {newFieldName: '$newFieldName'},
viewCount: {'$sum': 1}
}
},
{'$sort': {'_id.newFieldName': 1}}
], {})