我有一个错误集合,因此每个错误都带有一个 date
字段。如何仅按 DAY 聚合/计数/分组错误(即排除一天中的时间)?我想,应该应用一些智能投影。
最佳答案
您可以使用以下聚合运算符来做到这一点:
这将为您提供每个日期的错误计数:
db.errors.aggregate(
{ $group : {
_id: {
year : { $year : "$date" },
month : { $month : "$date" },
day : { $dayOfMonth : "$date" },
},
count: { $sum: 1 }
}}
);
此示例假定错误文档中的日期字段为 date
并且类型为 BSON Date . MongoDB 中还有一个 Timestamp 类型,但是 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.
https://stackoverflow.com/questions/15657501/