问题描述
我有一个错误集合,因此每个错误都带有一个 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:
这将为您提供每个日期的错误计数:
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 Timestamp 类型供 MongoDB 内部使用.对于大多数情况下,在应用程序开发中,您将希望使用 BSON 日期类型.有关详细信息,请参阅日期.
这篇关于在聚合框架中给出完整时间戳时如何按日期聚合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!