2019独角兽企业重金招聘Python工程师标准>>>
此处MongoDB的复杂的分页采用d调用MongoTemplate来实现
springboot中application.yml 配置
spring
data:
mongodb:
uri: mongodb://username:password@host:port/database
基本的查询可以通过 spring data jpa来实现,for example
public interface TestDao extends MongoRepository
}
1.编写MongoDB分页查询工具类,查询总条数以及分页的方法
/**
* 查询总条数
* @param operations
* @param collectionName
* @param clazz
* @return
*/
public long getTotalCount(List
Aggregation aggregationCount = Aggregation.newAggregation(operations);
List mappedResults = mongoTemplate.aggregate(aggregationCount, collectionName, clazz).getMappedResults();
if(null == mappedResults){
return 0;
}else{
return mappedResults.size();
}
}
/**
* collection的信息分页查询
* @param page
* @param pageSize
* @param sorts
* @param operations
* @param collectionName
* @param clazz
* @return
*/
public Page
String collectionName, Class clazz){
long totalCount = getTotalCount(operations,collectionName,clazz);
operations.add(Aggregation.skip((long) (page-1) * pageSize));
operations.add(Aggregation.limit(pageSize));
Aggregation aggregation = Aggregation.newAggregation(operations);
AggregationResults
Pageable pageable = PageRequest.of(page-1, pageSize, sorts);
return new PageImpl(results.getMappedResults(), pageable, totalCount);
}
2. 注入工具类,并使用聚合函数来添加设置查询条件
Sort sorts = null;
List
//设置排序
sorts = new Sort(Sort.Direction.ASC,sort);
operations.add(Aggregation.sort(Sort.Direction.ASC, sort));
//精确匹配
operations.add(Aggregation.match(Criteria.where("id").is(id)));
//使用正则表达式模糊匹配
Pattern pattern = Pattern.compile("^.*"+keyword+".*$", Pattern.CASE_INSENSITIVE);
operations.add(Aggregation.match(Criteria.where(LpConstants.KEYWORD).regex(pattern)));
//and or 组合
Criteria criteria1 = new Criteria().orOperator(Criteria.where("a").regex(pattern), Criteria.where("b").regex(pattern)); Criteria c = new Criteria().andOperator(new Criteria().where("id").is(id), criteria1); operations.add(Aggregation.match(c));
//日期比较
operations.add(Aggregation.match(Criteria.where("create_time").gte(format.parse(beginTime))));
operations.add(Aggregation.match(Criteria.where("create_time").lte(format.parse(endTime))));
Page