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

前端 未结 3 339
[愿得一人]
[愿得一人] 2020-12-08 04:55

I have a collection of errors, so that every error carries a date field. How can I aggregate/count/group the errors by DAY only (i.e. exclude the time of the da

相关标签:
3条回答
  • 2020-12-08 05:09

    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}}
    ], {})
    
    0 讨论(0)
  • 2020-12-08 05:18

    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.

    0 讨论(0)
  • 2020-12-08 05:20

    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 }
       }
     }
    ]);
    
    0 讨论(0)
提交回复
热议问题