mongodb mongotemplate聚合


1.group by並且計算總數

  @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部分去掉即可;
 
        

 2.Crieria的使用,注意andOperator和orOperator的用法

Aggregation agg = Aggregation.newAggregation(

    Aggregation.match(new Criteria()

            .andOperator(Criteria.where("onlineTime").gt(new Date()))

            .orOperator( Criteria.where("offlineTime").gt(new Date())

    ,Criteria.where("offlineTime").exists(false) ))

 3.Query的排序和分頁

Query query = new Query(Criteria.where(ReportField.GROUP_ID).in(groupIdList));
        query.with(new Sort(Direction.DESC, ReportField.ID));
        query.skip(lastId).limit(limit);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM