场景
按日期统计每日数据的条数,使用MongoTemplate实现按日期分组统计。
实现思路
先看看mongo命令怎么实现:
db.collection.aggregate([
{
$project: {date: {$dateToString: {format: "%Y-%m-%d", date: "$createTime"}}}
},
{$group: {_id: "$date", count: {$sum: 1}}},
{$project: {count: 1, _id: 0, date: "$_id"}},
{$sort: {"date": 1}}
])
对应的 java 实现:
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.project("createTime").and(DateOperators.DateToString.dateOf("createTime").toString("%Y-%m-%d")).as("date"),
Aggregation.group("date").count().as("count"),
Aggregation.project("date", "count").and("date").previousOperation(),
Aggregation.sort(Sort.Direction.ASC, "date")
);
AggregationResults<StatisticDayDTO> result = mongoTemplate.aggregate(aggregation, collectionName, StatisticDayDTO.class);
List<StatisticDayDTO> list = result.getMappedResults();
代码解释:
project:显示哪几个字段,这里显示createTime字段,and..as是把and后的字段重命名为as后的字段,这里把createTime处理后重命名为date
group:分组操作,这里按date分组,计算数量,结果数量重命名为count
第二个project:previousOperation方法是把_id重命名为date(也就是别名)
sort:结果按照date正序排序
collectionName: 集合名称
为了更好的理解and…previousOperation方法的含义,这里解释下:
去掉第二个project,结果形如[{"count": 3, "_id": "2019-12-13"}]
加上第二个project,结果形如[{"count": 3, "date": "2019-12-13"}]