springboot与mongodb之增删改查

作者: adm 分类: java 发布时间: 2023-12-25

一、引用mongoTemplate

    @Resource
    private MongoTemplate mongoTemplate;

二、分页查询
controller

@Resource
    private FillingRecordsService fillingRecordsService;

    @GetMapping("list")
    public Resultlist( @Validated PageValidate pageValidate){

        PageList list = fillingRecordsService.getList(pageValidate);
        return Result.OK(list);
    }

service

   @Resource
    MongoTemplate mongoTemplate;

    public PageList getList(PageValidate pageValidate ) {
        PageList pageList=new PageList();
        Query query = new Query();
        Criteria criteria = new Criteria();
       /* if (StringUtils.isNotBlank(platformId)) {
            criteria.and("platformId").is(platformId);
        }*/
        // 查询总数
        query.addCriteria(criteria);
        long count = mongoTemplate.count(query, FillingRecords.class);
        if (count <= 0) {
            return pageList;
        }
        // 按getPointDate进行降序排序并分页查询
        query.with(Sort.by(Sort.Order.desc("createdAt")))
                .skip((long)(pageValidate.getPage() - 1) * pageValidate.getLimit())
                .limit(pageValidate.getLimit());
        List list = mongoTemplate.find(query, FillingRecords.class);

        pageList.setTotal((int)count);
        pageList.setPage(pageValidate.getPage());
        pageList.setLimit(pageValidate.getLimit());
        pageList.setRecords(list);
        return pageList;
    }

返回参数

package cn.wmadmin.co2.member.vo;

import lombok.Data;

import java.util.List;

@Data
public class PageList {
    private int page;
    private int limit;
    private int total;
    private List records;
}

分页参数

package cn.wmadmin.co2.common.validate;

import io.swagger.annotations.ApiModel;
import lombok.Data;

import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import java.io.Serializable;

@Data
@ApiModel("分页参数")
public class PageValidate implements Serializable {

    private static final long serialVersionUID = 1L;

    // 当前分页
    @DecimalMin(value = "1", message = "page参数必须大于0的数字")
    public Integer page = 1;

    // 每页条数
    @DecimalMin(value = "1", message = "pageSize参数必须是大于0的数字")
    @DecimalMax(value = "60", message = "pageSize参数必须是小于60的数字")
    private Integer limit = 20;


}

三、保存数据

// 比较简单,data即为对象或者对象的集合
Data data = new Data();
data.setCode("123");
data.setName("测试");
mongoTemplate.insert(data, dbName);

四、修改数据

    public void testUpdate() {
        // 设置修改内容
        Update update = new Update();
        update.set("name", "测试2222");
        // 创建查询条件
        Criteria criteria = Criteria.where("code").in("123");
        Query updateQuery = new Query(criteria);
        // 更新数据
        mongoTemplate.updateMulti(updateQuery, update, "dbName");
    }

五、删除数据

    public void testDelete() {
        // 创建删除条件
        Criteria criteria = Criteria.where("code").in("123");
        Query deleteQuery = new Query(criteria);
        // 删除数据
        mongoTemplate.remove(deleteQuery, "dbName");
    }

六、聚合查询
注:聚合函数只能对数字类型的字段进行操作

    // 以平均查询为样例,聚合操作只支持数字类型的字段
    public void testAvg() {
        // 聚合集合
        List operations = new ArrayList<>();
        // 查询条件
        Criteria criteria = Criteria.where("code").in("123");
        MatchOperation match = Aggregation.match(criteria);
        // 设置分组条件,样例没有设置分组条件
        GroupOperation group = Aggregation.group();
        // 聚合操作
        group = group.avg("number1").as("avg").sum("number2").as("sum");
        operations.add(match);
        operations.add(group);
        Aggregation aggregation = Aggregation.newAggregation(operations);
        List aggregateList = mongoTemplate.aggregate(aggregation, "dbName", Map.class).getMappedResults();
        aggregateList.forEach(map -> {
            System.out.println(map.get("avg"));
            System.out.println(map.get("sum"));
        });
    }

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!