mongodb mongotemplate聚合

2018-10-11 10:51:18.0

主页 / 学习 / mongodb mongotemplate聚合

37

@Test

    public void insertTest() {

        //测试数据

        //insertTestData();

        Aggregation agg = Aggregation.newAggregation(

                //Aggregation.match(Criteria.where("groupId").is(5)),

                Aggregation.group("groupId").count().as("total"), 

                Aggregation.project("total").and("groupId").previousOperation(),            

                Aggregation.sort(Sort.DEFAULT_DIRECTION, "total"));

        List<StaCount> list = mongoTemplate.aggregate(agg, "currentUser", StaCount.class).getMappedResults();

        for(StaCount count : list) {

            System.out.println(count.getGroupId() + ":" + count.getTotal());

        }

  }

如果要带其他字段,将红字变为 Aggregation.group("groupId","groupName"...),并将project的and部分去掉即可;