• 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);
  • 相关阅读:
    localhost和127.0.0.1及ip区别
    Linux常用命令大全
    百度搜红包相关代码(1)
    今天开博第一篇,呵呵
    杯具啊,中考
    新年感想
    【转】汇编语言基础
    margin与padding
    .net 中的Literal Label 控件、Literal 控件、Panel 控件和 Placeholder 控件
    HTML 5 中的新元素
  • 原文地址:https://www.cnblogs.com/xiaoliu66007/p/14119994.html
Copyright © 2020-2023  润新知