java mongodb group后count,再排序

 

方式1:

Criteria criteria = new Criteria();
        criteria.andOperator(
                Criteria.where("msgTimestamp").gte(beginTime), Criteria.where("msgTimestamp").lte(endTime)
        );
        criteria.and("convType").is(ConvTypeEnum.PERSON.toString());
        if (StringUtils.isNotEmpty(fromAccount)) {
            criteria.and("fromAccount").is(Constants.TJK_PREFIX + fromAccount);
        }
        Sort sort0 = new Sort(Sort.Direction.DESC,"_id");

        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("relationId").count().as("ccc"),
                Aggregation.sort(sort0), Aggregation.limit(10000));
        List<DBObject> pvs =this.mongoTemplate().aggregate(aggregation, Constants.SINGLE_MSG_COLLECTION, DBObject.class).getMappedResults();

由于  db.teamTalkSingleMsg.aggregate([{$group : {_id : "$relationId", ccc : {$sum : 1}}}])这一行的“_id”不能写成其他的,所以排序也只能用_id来接

 

方式2:

//group
        DBObject groupFields = new BasicDBObject( "_id", "$relationId");
        groupFields.put("count", new BasicDBObject( "$sum", 1));
        DBObject group = new BasicDBObject("$group", groupFields);

//where条件
        DBObject condition1 = new BasicDBObject();
        condition1.put("convType", ConvTypeEnum.PERSON.toString());
        condition1.put("msgTimestamp", new BasicDBObject("$gte", beginTime).append("$lte", endTime));
        DBObject match = new BasicDBObject("$match", condition1); //$match相当于where

//排序
        DBObject sortFields = new BasicDBObject("_id", 1);
// 注意此处排序是按照字段day升序,但是不能写day 需用_id代替,因为day是group用的字段
        DBObject sort = new BasicDBObject("$sort", sortFields);

        List<DBObject> optionList = new ArrayList<>();
        optionList.add(match);
        optionList.add(group);
        optionList.add(sort);
//optionList中的顺序很重要,不是随便往list里面加的,否则是不正确的,添加的顺序也是参照上面网址里面的内容
        AggregationOutput output = this.mongoTemplate().getCollection(Constants.SINGLE_MSG_COLLECTION).aggregate(optionList);

 

posted @ 2020-12-11 13:53  君子笑而不语  阅读(1663)  评论(0编辑  收藏  举报