SpringBoot系列之MongoDBAggregations用法详解


当前第2页 返回上一页

统计用户名为User1的用户数量

 @Test
 public void matchCountTest() {
     Document first = collection.aggregate(
             Arrays.asList(match(Filters.eq("name", "User1")), count()))
             .first();
     log.info("count:{}" , first.get("count"));
     assertEquals(1 , first.get("count"));
 }

skip跳过记录,只查看后面5条记录

@Test
 public void skipTest() {
      AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(skip(5)));
      for (Document next : iterable) {
          log.info("user:{}" ,next);
      }

  }

对用户名进行分组,避免重复,group第一个参数$name类似于group by name,调用Accumulatorssum函数,其实类似于SQL,SELECT name ,sum(1) as sumnum FROMusergroup by name

@Test
 public void groupTest() {
     AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(
             group("$name" , Accumulators.sum("sumnum" , 1)),
             sort(Sorts.ascending("_id"))
             ));
     for (Document next : iterable) {
         log.info("user:{}" ,next);
     }

 }

参考资料

MongoDB 聚合 https://www.runoob.com/

MongoDB Aggregations Using Java

到此这篇关于SpringBoot系列之MongoDB Aggregations用法的文章就介绍到这了,更多相关SpringBoot MongoDB Aggregations用法内容请搜索


打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...