mongdb分组 年月日周

 //        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"}]
        Aggregation aggregation =
                Aggregation.newAggregation(Aggregation.project("createDate").and(DateOperators.DateToString.dateOf(
                        "createDate").toString("%Y%u")).as("date"), Aggregation.group("date").count().as("count"),
                        Aggregation.project("date", "count").and("date").previousOperation(),
                        Aggregation.sort(Sort.Direction.ASC, "date"));
        AggregationResults<Annex> result = mongoTemplate.aggregate(aggregation, "annex", Annex.class);
        Document rawResults = result.getRawResults();
        List lists = new ArrayList();
        List results = (List) rawResults.get("results");
        Map map = null;
        for(Object o : results){
            map = new HashMap<>();
            Object count = ((Document) o).get("count");
            Object date = ((Document) o).get("date");
            map.put("count", count);
            map.put("date", date);
            lists.add(map);
        }
        System.out.println(lists);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值