MongoDB按时间分组查询

对应数据库代码:

db.tshare_order.aggregate(
[
{$group:{
        _id:{ $dateToString: { format: "%Y-%m-%d", date: "$startTime" } },
         count:{$sum:1},
         qty: { $sum: "$orderAmount" },
         endcount: { $sum: "$sendMeterReal" }
         
        }
},
{ $project: { 
     日期: { $toUpper: "$_id" },
     订单需求量: "$count",
     送车米数: "$endcount",
     当日流水: "$qty",
     _id: 0 } 
},
{ $sort: { "_id": -1 } 
},
{$group:{
    _id:"$count" ,
         result: { push: "$endcount" }      
        }
},
]
)

在这里插入图片描述
对应java代码(不是很一样)
方法1:

//分组条件,按照天进行分组
        DBObject all = new BasicDBObject("_id",new BasicDBObject("month",new BasicDBObject("$month", "$startTime"))
                .append("day", new BasicDBObject("$dayOfMonth", "$startTime"))
                .append("year", new BasicDBObject("$year", "$startTime"))
        )
                .append("orderNeedCount",new BasicDBObject("$sum", 1))
                .append("dayMoneyCount",new BasicDBObject("$sum","$orderAmount"))
                ;
        //orderStatus

    // group
    DBObject group = new BasicDBObject("$group", all);
    DBObject condition1 = new BasicDBObject();
    condition1.put("startTime",new
            BasicDBObject("$lte",new Date()));//注意这边时间是要data类型
    DBObject match = new BasicDBObject("$match", condition1); // $match相当于where
    // 排序
    DBObject sortFields = new BasicDBObject("startTime", -1);
    // 注意此处排序是按照字段day升序,但是不能写day 需用_id代替,因为day是group用的字段
    DBObject sort = new BasicDBObject("$sort", sortFields);
    //List需要按照顺序添加
    List<DBObject> optionList = new ArrayList<>();
    optionList.add(match);
    optionList.add(group);
    optionList.add(sort);
    AggregationOutput output = mongoTemplate.getCollection("tshare_order").aggregate(optionList);
    for (DBObject obj : output.results()) {
        System.out.println("是卿卿"+obj);
    }
    Iterable<DBObject> list = output.results();

方法2.

        DateOperators.DateToString a = DateOperators.DateToString.dateOf("startTime").toString("%Y-%m-%s");
        String b =a.toString();
        Aggregation agg = Aggregation.newAggregation(
                group(DateOperators.DateToString.dateOf("startTime").toString("%Y-%m-%s").toString()).count().as("count")
                );
        System.out.println("11111111111111111111111"+agg);
        AggregationResults<TshareOrder> orderResults = mongoTemplate.aggregate(agg, "tshare_order", TshareOrder.class);
        List<TshareOrder> list = orderResults.getMappedResults();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值