SpringBoot系列之MongoDB Aggregations用法

x33g5p2x  于2022-02-09 转载在 Go  
字(2.3k)|赞(0)|评价(0)|浏览(276)

1、前言

在上一章的学习中,我们知道了Spring Data MongoDB的基本用法,但是对于一些聚合操作,还是不熟悉的,所以本博客介绍一些常用的聚合函数

2、什么是聚合?

MongoDB 中使用聚合(Aggregations)来分析数据并从中获取有意义的信息。在这个过程,一个阶段的输出作为输入传递到下一个阶段

  • 常用的聚合函数
聚合函数SQL类比描述
projectSELECT类似于select关键字,筛选出对应字段
matchWHERE类似于sql中的where,进行条件筛选
groupGROUP BY进行group by分组操作
sortORDER BY对应字段进行排序
countCOUNT统计计数,类似于sql中的count
limitLIMIT限制返回的数据,一般用于分页
outSELECT INTO NEW_TABLE将查询出来的数据,放在另外一个document(Table) , 会在MongoDB数据库生成一个新的表

3、环境搭建

开发环境

  • JDK 1.8

  • SpringBoot2.2.1

  • Maven 3.2+

  • 开发工具

  • IntelliJ IDEA

  • smartGit

  • Navicat15

使用阿里云提供的脚手架快速创建项目:
https://start.aliyun.com/bootstrap.html

也可以在idea里,将这个链接复制到Spring Initializr这里,然后创建项目

jdk选择8的

选择spring data MongoDB

4、数据initialize

private static final String DATABASE = "test";
private static final String COLLECTION = "user";
private static final String USER_JSON = "/userjson.txt";
private static MongoClient mongoClient;
private static MongoDatabase mongoDatabase;
private static MongoCollection<Document> collection;

@BeforeClass
public static void init() throws IOException {
    mongoClient = new MongoClient("192.168.0.61", 27017);
    mongoDatabase = mongoClient.getDatabase(DATABASE);
    collection = mongoDatabase.getCollection(COLLECTION);

    collection.drop();

    InputStream inputStream = MongodbAggregationTests.class.getResourceAsStream(USER_JSON);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    reader.lines()
            .forEach(l->collection.insertOne(Document.parse(l)));
    reader.close();

}

5、例子应用

本博客,不每一个函数都介绍,通过一些聚合函数配置使用的例子,加深读者的理解

  • 统计用户名为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);
     }

 }

参考资料

相关文章

微信公众号

最新文章

更多