1. 程式人生 > >springboot下使用MongoTemplate查詢、聚合、分頁mongodb

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的分頁優化,暫時自己沒有親測。