我有一个错误集合,因此每个错误都包含一个date字段.如何仅按DAY(即排除一天中的时间)汇总/计数/分组错误?我猜应该应用一些精巧的投影.
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 day)? I guess, some smart projection should be applied.
推荐答案您可以通过使用以下聚合运算符来做到这一点:
You can do this by using the following aggregation operators:
- $ group
- $ year
- $ month
- $ dayOfMonth
- $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 } }} );此示例假定错误文档中的日期字段为date,类型为 BSON日期. 文档明确建议不要在MongoDB中使用Timestamp类型,但强烈建议不要使用此类型:
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:
注意:BSON时间戳类型供内部MongoDB使用.对于大多数 情况下,在应用程序开发中,您将需要使用BSON日期 类型.有关更多信息,请参见日期.
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.
更多推荐
在汇总框架中提供完整时间戳时,如何按日期汇总?
发布评论