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);

  • 7
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用MongoTemplate进行聚合查询来获取数据总数,您可以使用Aggregation类和AggregationOperation接口来构建聚合查询。以下是使用MongoTemplate查询名为attendance的集合中数据总数的示例代码: ```java import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationResults; import org.springframework.data.mongodb.core.aggregation.CountOperation; import org.springframework.data.mongodb.core.query.Criteria; public class Main { private final MongoTemplate mongoTemplate; public Main(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } public long getAttendanceCount() { CountOperation countOperation = Aggregation.count().as("count"); Aggregation aggregation = Aggregation.newAggregation( Aggregation.match(Criteria.where("collectionName").is("attendance")), countOperation ); AggregationResults<CountResult> results = mongoTemplate.aggregate(aggregation, "system.namespaces", CountResult.class); CountResult countResult = results.getUniqueMappedResult(); if (countResult != null) { return countResult.getCount(); } else { return 0; } } public static void main(String[] args) { // 创建MongoTemplate实例 // MongoTemplate mongoTemplate = ...; Main main = new Main(mongoTemplate); long count = main.getAttendanceCount(); System.out.println("Attendance count: " + count); } private static class CountResult { private long count; public long getCount() { return count; } public void setCount(long count) { this.count = count; } } } ``` 请确保已经创建了MongoTemplate实例,并将其传递给Main类的构造函数。然后,可以调用getAttendanceCount方法来执行聚合查询并获取名为attendance的集合中的数据总数。聚合查询通过匹配条件来筛选出名为attendance的集合,然后使用count操作来计算文档数量。最后,从聚合结果中提取计数并返回。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值