MongoTemplate 基础使用

k8s 部署 MongoDB 三种模式:https://blog.csdn.net/weixin_42555971/article/details/126243336
 

开始

pom 配置 文件

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

springboot 版本:2.5.x
配置 application.yml
uri实例:mongodb://root:password@192.168.101.01:30017/database

spring:
  data:
    mongodb:
      uri:  mongodb://[用户名]:[密码]@[ip]:[端口]/[数据库]

springboot 版本:2.7.x
配置 application.yml

spring:
  data:
    mongodb:
      host: 192.168.101.01
      port: 30017
      database: test
      authentication-database: admin
      username: root
      password: password

 

引入

springframework 提供的 MongoDB 查询工具

  1. mongoTemplate: 封装较为完整,外露接口使用清晰方便
  2. mongoOperations:方法更多一些,也更接近于mongo的原生态语言。而 mongoTemplate 就是 mongoOperations 的一个实现
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@Resource
MongoTemplate mongoTemplate;

@Resource
MongoOperations mongoOperations;

使用 TestPO 做例子

@Data
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "test")
public class TestPO {

    /**
     * 唯一标识.
     */

    private Long id;

    /**
     * 名称
     */
    private String name;

    /**
     * 描述
     */
    private String description;
}

 

增删改查

新增:insert

@PostMapping("/test")
public Result<String> insert() throws Exception {
    TestPO testPO = new TestPO(RandomUtils.nextLong(), "name" + RandomUtils.nextLong(), "description" + RandomUtils.nextLong());
    mongoTemplate.insert(testPO);
    return Result.success("创建成功!", null);
}

修改:save

@PutMapping("/test")
public Result<String> update(@RequestBody TestPO testPO) throws Exception {
    mongoTemplate.save(testPO);
    return Result.success("更新成功!", null);
}

删除:remove

    @DeleteMapping("/test/{id}")
    public Result<String> delete(@PathVariable Long id) throws Exception {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, TestPO.class);
        log.info("query-delete");
        return Result.success("物理删除成功!", null);
    }

单个查询:findById

    @GetMapping("/query/{id}")
    public Result<TestPO> getQuery(@PathVariable Long id) throws Exception {
        TestPO info = mongoTemplate.findById(id, TestPO.class);
        return Result.success("查询成功!", info);
    }

列表查询:findAll

public Result<List<TestPO>> listQuery() throws Exception {
    List<TestPO> list = mongoTemplate.findAll(TestPO.class);
    return Result.success("列表查询成功!", list);
}

分页查询:mongoOperations

  1. Pageable:组装 每页大小、第几页、排序
  2. Query :创建查询条件
  3. count:计算总条数
  4. find:查询符合条件的数据
  5. getPage:实现分页
Pageable page = PageRequest.of(req.getPage() - 1, req.getSize(), Sort.Direction.DESC, "id");
Query query = new Query();
long count = mongoOperations.count(query, TestPO.class);
query.with(page);

List<TestPO> list = mongoOperations.find(query, TestPO.class, "test");
Page<TestPO> doPage = PageableExecutionUtils.getPage(list, page, () -> count);

 

条件查询

列表查询,模糊查询:Criteria 使用 regex 正则表达式

    public Result<List<TestPO>> listQueryLike() throws Exception {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").regex(".*" + "nn" + ".*"));
        List<TestPO> list = mongoTemplate.find(query, TestPO.class);
        return Result.success("列表查询成功!", list);
    }

列表查询,and 查询:Query 添加多个 Criteria

public Result<List<TestPO>> listQueryAnd() throws Exception {
    Query query = new Query();
    query.addCriteria(Criteria.where("name").regex(".*" + "nn" + ".*"));
    query.addCriteria(Criteria.where("description").regex(".*" + "dd" + ".*"));
    List<TestPO> list = mongoTemplate.find(query, TestPO.class);
    log.info("query-list-many");
    return Result.success("列表查询成功!", list);
}

列表查询,or 查询:Criteria 使用 orOperator,orOperator 的传参为 Criteria 数组

public Result<List<TestPO>> listQueryOr() throws Exception {
    Query query = new Query();
    query.addCriteria(new Criteria().orOperator(
            Criteria.where("name").regex(".*" + "nn" + ".*"),
            Criteria.where("description").regex(".*" + "dd" + ".*"))
    );
    List<TestPO> list = mongoTemplate.find(query, TestPO.class);
    log.info("query-list-many");
    return Result.success("列表查询成功!", list);
}

分页查询,添加条件

  1. Pageable:组装 每页大小、第几页、排序
  2. Query :创建查询条件
  3. Criteria:添加查询条件
  4. count:计算总条数
  5. find:查询符合条件的数据
  6. getPage:实现分页
Pageable page = PageRequest.of(req.getPage() - 1, req.getSize(), Sort.Direction.DESC, "id");
Query query = new Query();
query.addCriteria(new Criteria().orOperator(
        Criteria.where("name").regex(".*" + "nn" + ".*"),
        Criteria.where("description").regex(".*" + "dd" + ".*"))
);
long count = mongoOperations.count(query, TestPO.class);
query.with(page);

List<TestPO> list = mongoOperations.find(query, TestPO.class, "test");
Page<TestPO> doPage = PageableExecutionUtils.getPage(list, page, () -> count);

 

批量操作

批量插入,insert:传参为实体 list

TestPO testPO1 = new TestPO("name" + RandomUtils.nextLong(), "description" + RandomUtils.nextLong());
TestPO testPO2 = new TestPO("name" + RandomUtils.nextLong(), "description" + RandomUtils.nextLong());
List<TestPO> list = new ArrayList<>();
list.add(testPO1);
list.add(testPO2);
mongoTemplate.insert(list);

批量更新

  1. 组装 List<Pair<Query, Update>>
  2. BulkMode.UNORDERED:表示并行处理,遇到错误时能继续执行不影响其他操作;
  3. BulkMode.ORDERED:表示顺序执行,遇到错误时会停止所有执行
  4. upsert:批量更新
  5. execute:执行
List<Pair<Query, Update>> pairList = getPairList(list);
BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, TestPO.class);
operations.upsert(pairList);
operations.execute();

获取 PairList

  1. 循环取实体 T,格式化为 Pair<Query, Update>
  2. 实体 T 通过 ObjectMapper 转为 String
  3. String T 格式化为 Document
  4. document 获取 id 字段的值后将其删除 ,因为 id 不需更新
  5. 把 id 的值加入查询条件 query
  6. 把 document 里的 key - value 对应关系映射到 update
  7. Pair.of 组装成 Pair<Query, Update>
public static <T> List<Pair<Query, Update>> getPairList(List<T> list) throws JsonProcessingException {
    List<Pair<Query, Update>> pairList = new LinkedList<>();
    for (T t : list) {
        // 循环获取Pair对象
        Pair<Query, Update> pair = getPair(t);
        pairList.add(pair);
    }
    return pairList;
}

private static <T> Pair<Query, Update> getPair(T t) throws JsonProcessingException {
    Query query = new Query();
    Update update = new Update();
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(t);
    Document document = objectMapper.readValue(json, Document.class);
    // 删除key为“_id”的键值对,同时返回value
    Object id = document.remove("id");
    // 指定查询字段
    query.addCriteria(Criteria.where("id").is(id));
    // 指定更新字段
    document.forEach(update::set);
    // 如果你不想更新目标对象为null的字段,使用下列forEach函数替代上一行代码
    /*document.forEach((key, value)->{
        if(ObjectUtils.isNotEmpty(value)){
            update.set(key, value);
        }
    });*/
    // 返回Pair对象
    return Pair.of(query, update);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值