springboot下使用MongoTemplate查询、聚合、分页mongodb

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:[email protected]:27017/test

3.使用

3.1在使用类中直接注入

    @Autowired
    MongoTemplate mongoTemplate;

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的分页优化,暂时自己没有亲测。

猜你喜欢

转载自blog.csdn.net/yzh_1346983557/article/details/83146931
今日推荐