Mongodb按照日期分组统计

Posted xibuhaohao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mongodb按照日期分组统计相关的知识,希望对你有一定的参考价值。


mongodb的默认时间是格林尼治时间,如果是要按照日期进行分组需要注意!!!。
解决方案:

1.使用时间格式化方法

Aggregation.project().and("createTime").dateAsFormattedString("%Y-%m-%d").as("time"),
Aggregation.group("time").count().as("count")

或者

Aggregation.project().and(DateOperators.DateToString.dateOf("createTime").toString("%Y-%m-%d")).as("name"),
Aggregation.group("time").count().as("count")

dateAsFormattedString()方法会默认将当前时间转为系统默认的时区

2.进行时间补偿(默认当前时区是东八区,即8x3600x1000=28800000)

Aggregation.project().andExpression("add(createTime,28800000)").as("time"),
Aggregation.group("time").count().as("count")

以上是关于Mongodb按照日期分组统计的主要内容,如果未能解决你的问题,请参考以下文章