SpringBoot MongoDB操作封装

1.引入Jar包

XML 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

2.MongoDbHelper操作

java 复制代码
/**
 * MongoDB Operation class
 * @author Mr.Li
 * @date 2022-12-05
 */
public class MongoDbHelper {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * Save Individual Objects
     *
     * @param t
     * @param <T>
     * @return
     */
    public <T> T save(T t) {
        return mongoTemplate.insert(t);
    }

    /**
     * Store the object to the specified collectionName
     * @param objectToSave
     * @param collectionName
     * @param <T>
     * @return
     */
    public <T> T save(T objectToSave, String collectionName){
        return mongoTemplate.insert(objectToSave,collectionName);
    }

    /**
     * Batch save track data
     *
     * @param list
     * @param collectionName
     * @return
     */
    public <T> Collection<T> batchSave(Collection<T> list, String collectionName) {
        return mongoTemplate.insert(list,collectionName);
    }
    
    /**
     * Query Data
     *
     * @param query
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> List<T> find(Query query, Class<T> tClass) {
        return mongoTemplate.find(query, tClass);
    }

    /**
     * Collection specified by query data
     *
     * @param query
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> List<T> find(Query query, Class<T> tClass, String collectionName) {
        return mongoTemplate.find(query, tClass,collectionName);
    }

    /**
     * Pagination query
     * @param query query criteria
     * @param pageNum Current Page
     * @param pageSize Number of entries per page
     * @param sortField Sorted Field
     * @param sortType 1:asc;0:desc
     * @param tClass to class
     * @param collectionName collection name
     * @param <T>
     * @return
     */
    public <T> MongoPage findByPage(Query query,int pageNum,int pageSize,String sortField,int sortType, Class<T> tClass, String collectionName) {
        int count = (int) mongoTemplate.count(query, tClass, collectionName);
        if(sortType==1){
            query.with(Sort.by(Sort.Order.asc(sortField)));
        }else {
            query.with(Sort.by(Sort.Order.desc(sortField)));
        }
        //Set starting number
        query.skip((pageNum - 1) * pageSize);
        //Set the number of queries
        query.limit(pageSize);
        //Query the current page data set
        List<T> taskList = mongoTemplate.find(query, tClass,collectionName);
        int size=count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        MongoPage page=new MongoPage();
        page.setTotal(count);
        page.setSize(size);
        page.setData(taskList);
        return page;
    }

    /**
     * 查询前几条数据
     * @param query
     * @param limitNum 前几条
     * @param sortField 排序字段
     * @param sortType 0:倒序;1:正序
     * @param tClass
     * @param collectionName
     * @param <T>
     * @return
     */
    public <T> List<T> findTop(Query query,Integer limitNum,String sortField,int sortType, Class<T> tClass, String collectionName){
        if(sortType==1){
            query.with(Sort.by(Sort.Order.asc(sortField)));
        }else {
            query.with(Sort.by(Sort.Order.desc(sortField)));
        }
        query.limit(limitNum);
        return mongoTemplate.find(query, tClass,collectionName);
    }

    /**
     * 查询一条数据
     * @param query
     * @param sortField
     * @param sortType
     * @param tClass
     * @param collectionName
     * @param <T>
     * @return
     */
    public <T> List<T> findOne(Query query,String sortField,int sortType, Class<T> tClass, String collectionName){
        if(sortType==1){
            query.with(Sort.by(Sort.Order.asc(sortField)));
        }else {
            query.with(Sort.by(Sort.Order.desc(sortField)));
        }
        //Set the number of queries
        query.limit(1);
        //Query the current page data set
        List<T> taskList = mongoTemplate.find(query, tClass,collectionName);
        return taskList;
    }

    /**
     * Query All
     *
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> List<T> findAll(Class<T> tClass) {
        return mongoTemplate.findAll(tClass);
    }

    /**
     * Query all specified collections
     *
     * @param tClass
     * @param collectionName
     * @param <T>
     * @return
     */
    public <T> List<T> findAll(Class<T> tClass,String collectionName) {
        return mongoTemplate.findAll(tClass,collectionName);
    }

    /**
     * create collection
     * @param collName
     * @param indexList
     * @return
     */
    public boolean createCollection(String collName, List<Map<String,Integer>> indexList){
        try {
            if (mongoTemplate.collectionExists(collName)) {
                return true;
            }
            //Index collection to be created
            List<IndexModel> indexModels = new ArrayList<>();
            for (Map<String, Integer> indexMap : indexList) {
                BasicDBObject index = new BasicDBObject();
                for (String key : indexMap.keySet()) {
                    index.put(key, indexMap.get(key));
                }
                indexModels.add(new IndexModel(index));
            }
            mongoTemplate.createCollection(collName).createIndexes(indexModels);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * Update the first result set returned by the query
     * @param query
     * @param update
     * @param collectionName
     * @return
     */
    public boolean updateFirst(Query query, Update update, String collectionName){
        try {
            mongoTemplate.updateFirst(query, update, collectionName);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * Update all returned result sets
     * @param query
     * @param update
     * @param collectionName
     * @return
     */
    public boolean updateMulti(Query query, Update update, String collectionName){
        try {
            mongoTemplate.updateMulti(query, update, collectionName);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * If the update object does not exist, add it
     * @param query
     * @param update
     * @param tClass
     * @param <T>
     * @param collectionName
     * @return
     */
    public <T> boolean upsert(Query query, Update update, Class<T> tClass,String collectionName){
        try {
            mongoTemplate.upsert(query, update, tClass,collectionName);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 存在则更新不存在则创建
     * @param query
     * @param update
     * @param collectionName
     * @return
     */
    public boolean upsert(Query query, Update update, String collectionName){
        try {
            mongoTemplate.upsert(query, update,collectionName);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 汇总查询
     * @param aggregation
     * @param tClass
     * @param collectionName
     * @param <T>
     * @return
     */
    public <T> List<T> groupQuery(Aggregation aggregation,Class<T> tClass,String collectionName){
        AggregationResults<T> maps = mongoTemplate.aggregate(aggregation, collectionName, tClass);
        return maps.getMappedResults();
    }

    /**
     * 查总条数
     * @param query
     * @param collectionName
     * @return
     */
    public long queryCount(Query query, String collectionName){
        return mongoTemplate.count(query, collectionName);
    }
}

3.分页实体类MongoPage

java 复制代码
/**
 * MongoDB paged query returns result set
 * @author Mr.Li
 * @date 2023-01-11
 */
@Data
public class MongoPage {
    /**
     * Total number of data
     */
    private Integer total;

    /**
     * Page count
     */
    private Integer size;

    /**
     * Data result set per page
     */
    private Object data;
}
相关推荐
向前看-3 小时前
验证码机制
前端·后端
你的微笑,乱了夏天4 小时前
linux centos 7 安装 mongodb7
数据库·mongodb
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭5 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
超爱吃士力架5 小时前
邀请逻辑
java·linux·后端
AskHarries7 小时前
Spring Cloud OpenFeign快速入门demo
spring boot·后端
isolusion8 小时前
Springboot的创建方式
java·spring boot·后端
Yvemil78 小时前
《开启微服务之旅:Spring Boot Web开发举例》(一)
前端·spring boot·微服务
zjw_rp8 小时前
Spring-AOP
java·后端·spring·spring-aop
TodoCoder9 小时前
【编程思想】CopyOnWrite是如何解决高并发场景中的读写瓶颈?
java·后端·面试
凌虚9 小时前
Kubernetes APF(API 优先级和公平调度)简介
后端·程序员·kubernetes