springboot使用MongoTemplate查询、聚合、分页、多条件拼接

1.maven的pom.xml中引入jar包

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

2.配置文件application.properties中配置mongodb地址

## mongodb ##
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/test

若连接需要账号验证,改为:

spring.data.mongodb.uri=mongodb://root:root@127.0.0.1:27017/test

3.使用

在使用类中直接注入

@Service
public class MongoService {
    @Resource
    MongoTemplate mongoTemplate;
}

3.1查询

        Query query = new Query(Criteria.where("type").is(type).and("name").is(name));
        List<ReportRealtime> reportRealtimeModel = mongoTemplate.find(query, ReportRealtime.class);
        // 指定collectionName。不指定默认是类名的驼峰格式:reportRealtime
        // List<ReportRealtime> reportRealtimeModel = mongoTemplate.find(query, ReportRealtime.class, "reportRealtimeModel");

3.2聚合

        String alias = "nowNum";
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("name").is(name)),
                Aggregation.group("age").count().as(alias)
        );
        AggregationResults<Map> results= mongoTemplate.aggregate(aggregation, "testCollection", Map.class);
        List<Map> mappedResults = results.getMappedResults();
        if (mappedResults != null && mappedResults.size() > 0) {
            Integer num = (Integer) mappedResults.get(0).get(alias);
            return num;
        }

3.3多条件聚合查询

        String alias = "nowNum";
        Aggregation aggregation = Aggregation.newAggregation(                                
Aggregation.match(Criteria.where("name").is(name).and("size").is(size)),
//Aggregation.match(Criteria.where("size").is(size)),
                Aggregation.group("age").count().as(alias)
        );
        AggregationResults<Map> results= mongoTemplate.aggregate(aggregation, "testCollection", Map.class);
        List<Map> mappedResults = results.getMappedResults();
        if (mappedResults != null && mappedResults.size() > 0) {
            Integer num = (Integer) mappedResults.get(0).get(alias);
            return num;
        }

3.4分页查询

        Query query = new Query(Criteria.where("name").is(name).and("size").is(size).and("age").is(age))
            .skip((page.getPageNum() - 1) * page.getPageSize())
            .limit(page.getPageSize());
        List<JavaEntity> list = mongoTemplate.find(query, JavaEntity.class, "testCollection");
        long totalSize = mongoTemplate.count(query, JavaEntity.class, "testCollection");
        page.setTotalSize((int) totalSize);

注意:分页查询是最基本的查询,看网上说法,这种查询会导致mongodb的全表查询,即整个collection的查询,所以collection的数据量大的时候不建议使用这种方式,具体可百度mongodb的分页优化,暂时自己没有亲测。

3.5多条件拼接

        Criteria criteria = new Criteria();
        if (StringUtils.isNotBlank(state)) {
            // 精准查询
            criteria.and("state").is(state);
        }
        if (StringUtils.isNotBlank(name)) {
            // 模糊查询
            Pattern pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
            criteria.and("name").regex(pattern);
        }
        if (groupIdList != null && groupIdList.size() > 0) {
            // 集合查询
            criteria.and("groupId").in(groupIdList);
        }
        if (StringUtils.isNotBlank(terminalId)) {
            // 多字段模糊 或 查询
            Pattern pattern = Pattern.compile("^.*" + terminalId + ".*$", Pattern.CASE_INSENSITIVE);
            criteria.orOperator(
                Criteria.where("terminalId").regex(pattern),
                Criteria.where("terminalName").regex(pattern)
            );
        }
        // 时间范围查询
        if (startTime != null && endTime != null) {
            criteria.andOperator(
                Criteria.where("updateTime").gte(new Date(startTime)),
                Criteria.where("updateTime").lte(new Date(endTime))
            );
        } else if (startTime != null && endTime == null) {
            criteria.and("updateTime").gte(new Date(startTime));
        } else if (startTime == null && endTime != null) {
            criteria.and("updateTime").lte(new Date(endTime));
        }

        // 分页
        Query query = new Query(criteria).skip((pageNum - 1) * pageSize).limit(pageSize);


版权声明:本文为yzh_1346983557原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。