MongoDB

区别于关系型数据库,MongoDB 需要额外的接口来解决特定问题。

创建实例

Unabo.nosql.load("mongo", configurationNosql -> {
    configurationNosql.setIp("127.0.0.1");
    configurationNosql.setPort(27017);
    configurationNosql.setSchema("test");
    configurationNosql.setUsername("root");
    configurationNosql.setPassword("123456");
});

Pipeline 管道模式

Pipeline 接口是有序管道处理数据,即下一管道的输入是上一管道的输出。用于子表字段展开、分组统计等。

Unwind

展开数组字段:

bootstrap.pipeline("user")
    // 展开 child 字段
    .unwind("child") 
    // 映射指定输出字段
    .project("id", "name", "age", "child.name", "child.age")
    // 别名
    .alias(Collections.asMap("child.name", "cName", "child.age", "cAge"))
    // 添加条件
    .addCondition(conds -> conds.add(gte("age", 18)))
    .maps();

Group

分组统计:

List<Document> maps = bootstrap.pipeline("group")
    // 用 name 分组,查询 score 平均值和分组后第一个 sex
    .group(java.util.Collections.singletonList("name"), 
        Aggregation.newInstance()
            .avg("score")
            .first("sex"))
    // 分组后字段名会自动带上标识
    .project("score_avg","sex_first","name")
    // 根据结果需要,通过别名去掉标识
    .alias(Collections.asMap("score_avg","score","sex_first","sex"))
    .maps();

Aggregate

聚合操作:

bootstrap.pipeline("user")
    .aggregate(
        Collections.singletonList(
            Aggregation.newInstance().count()
        )
    )
    .maps();

Aggregate Pipeline

聚合管道:

bootstrap.pipeline("user")
    .aggregatePipeline(
        Arrays.asList(
            new Document("$match", new Document("age", new Document("$gte", 18))),
            new Document("$group", new Document("_id", "$name").append("count", new Document("$sum", 1)))
        )
    )
    .maps();

事务

MongoDB 事务需集群配置,开发环境至少支持单副本节点。

配置事务工厂

unabo:
  enable: true
  nosql-instances:
    - id: bootstrap
      ip: 127.0.0.1
      port: 27017
      username: root
      password: 123456
      schema: nocode
      transaction-factory: MongoDBTransactionFactory
      show-log: false

使用事务

使用 openSession 方法开启事务,异常自动回滚:

bootstrap.openSession(() -> {
    // 数据库操作
});

捕获异常不会影响事务回滚:

try {
    bootstrap.openSession(() -> {
        // 数据库操作
    });
} catch(Exception e) {
    e.printStackTrace();
}

视图

创建视图:

bootstrap.queryTable("user")
    .createView("user_view", 
        Collections.singletonList(new Document("$match", new Document("status", "active")))
    );

ElementMatch

查询数组中满足条件的元素:

bootstrap.queryTable("user")
    .addCondition(C.elementMatch("tags", C.eq("name", "java")))
    .list();

与 SQL 操作对比

操作SQLMongoDB
创建表CREATE TABLEqueryEntity().create()
插入数据INSERT INTOquery().insert()
查询数据SELECT FROMqueryTable().list()
更新数据UPDATE SETquery().update()
删除数据DELETE FROMqueryTable().delete()
聚合查询GROUP BYpipeline().group()
数组展开pipeline().unwind()