How to aggregate by date when a full timestamp is given in aggregation framework?

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.

Leave a Comment