使用spring-data-mongodb对mongo进行联表分页查询

对应mongo的sql语句
查询总数量

db.getCollection('user').aggregate([
{
    $lookup: { // 左连接
        from: "dialog", // 关联到的表
        localField: "_id", // user 表关联的字段
        foreignField: "usersId", // dialog 表关联的字段
        as: "dialog"
    }
 },
 { 
     $match:{  
         "dialog.valid":{"$exists":true}
     }
 },
 {
     $group: {
        _id: null,
        count: { $sum: 1 }
     }
   }
    ])

注意:
1、低版本的mongo不支持联表查询。
2、关联的两个字段,数据类型必须一致。

对应的代码如下:

        Criteria criteria = getCriteria(searchForm);
		//查询总数量
        Aggregation aggCount = Aggregation.newAggregation(
                Aggregation.lookup("dialog", "_id", "usersId", "dialog"),
                Aggregation.match(criteria),
                Aggregation.group("_id:null").count().as("count")
        );
        AggregationResults<Map> resultCount = mongoTemplate.aggregate(aggCount,"user", Map.class);
        List<Map> userListCount = resultCount.getMappedResults();
        log.info("userListCount   {}", userListCount);
        long count = 0L;
        if(userListCount != null && userListCount.size() > 0){
            count = Long.parseLong(userListCount.get(0).get("count").toString());
        }
        //分页查询
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.lookup("dialog", "_id", "usersId", "dialog"),
                Aggregation.match(criteria),
                Aggregation.skip(pageable.getOffset()),
                Aggregation.limit(pageable.getPageSize())
        );
        AggregationResults<User> result = mongoTemplate.aggregate(agg,"user", User.class);
        List<User> userList = result.getMappedResults();
        log.info("userList {}", userList);
        return new PageImpl<>(userList, pageable, count);

代码注意点:
lookup联表查询在前,match在后。不然查询为空。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值