python mongodb分页查询_MongoDB分页以及复杂条件查询例子

此处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 operations,String collectionName,Class clazz){

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 getPageList(int page, int pageSize, Sort sorts, List operations,

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 results = mongoTemplate.aggregate(aggregation,collectionName,clazz);

Pageable pageable = PageRequest.of(page-1, pageSize, sorts);

return new PageImpl(results.getMappedResults(), pageable, totalCount);

}

2. 注入工具类,并使用聚合函数来添加设置查询条件

Sort sorts = null;

List operations = new ArrayList<>();

//设置排序

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 = newCriteria().orOperator(Criteria.where("a").regex(pattern),

Criteria.where("b").regex(pattern));

Criteria c = newCriteria().andOperator(newCriteria().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 page = mongoDao.getPageList(page,pageSize,sorts,operations,"collectionName",Test.class);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值