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" }      
        }
},
]
)

MongoDB按时间分组查询_第1张图片
对应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 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 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 orderResults = mongoTemplate.aggregate(agg, "tshare_order", TshareOrder.class);
        List list = orderResults.getMappedResults();

你可能感兴趣的:(java,mongoDB)