mongodb 在聚合框架中给出完整时间戳时如何按日期聚合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15657501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to aggregate by date when a full timestamp is given in aggregation framework?
提问by BreakPhreak
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.
我有一系列错误,因此每个错误都带有一个date
字段。如何仅按天汇总/计数/分组错误(即排除一天中的时间)?我想,应该应用一些智能投影。
回答by Philipp
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 }
}}
);
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 Datedate
类型。MongoDB 中还有一个 Timestamp 类型,但文档明确不鼓励使用这种类型:
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.
注意:BSON 时间戳类型供内部 MongoDB 使用。大多数情况下,在应用程序开发中,您会希望使用 BSON 日期类型。有关详细信息,请参阅日期。
回答by Dmitry Sergeev
You can convert your timestamp field to string with specific date format by using $project (aggregation)
您可以使用$project (aggregation)将时间戳字段转换为具有特定日期格式的字符串
aggregate([
{
'$project': {
newFieldName: {'$dateToString': {format: '%Y-%m-%d', date: '$yourDateFieldName'}}
}
}, {
'$group': {
_id: {newFieldName: '$newFieldName'},
viewCount: {'$sum': 1}
}
},
{'$sort': {'_id.newFieldName': 1}}
], {})