对应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在后。不然查询为空。