java操作mongodb之多表联查的实现($lookup)

网友投稿 279 2023-01-24

java操作mongodb之多表联查的实现($lookup)

最近在开发的过程中,一个列表的查询,涉及到了多表的关联查询,由于持久层使用的是mongodb,对这个非关系型数据使用的不是很多,所以在实现此功能的过程中出现了不少问题,现在此做记录,一为加深自己的理解,以后遇到此类问题可以快速的解决,二为遇到同样问题的小伙伴提供一点小小的帮助。

全文分为两部分:

使用robo3t编写多表关系的查询语句

将编写的查询语句整合到java项目

多表联查的查询语句:

此处使用的为mongodb的robo3t可视化工具,先说下需求:从A(假如说是日志表)表中查询出符合条件的数据,根据A表中符合条件数据查询B(假如说是信息表)表中的数据,此处也可以将B表的查询条件加入进来(类型于关系型数据库中的临时表)

mongo查询语句:

db.getCollection('A').aggregate([

{

$lookup:{

from:'B',

localField:'userid',

foreignField:'userid',

as:'userinfo'

}

},

{

$unwind:'$userrole'//把一个数组展成多个,就比如说按多表连查的userrole数组中有10数据,那么用$unwind将把一条带数组的数据分成10条,这10条数据除了userrole不同之外,其它数据都是相同的,就类似于一个展开操作

},

{

$match:{'username':'zhangsan'}

},

{

$group:{

_id:{

userid:'$userid',//这个属性必须是要A表中有的

userrole:'$userrole.roleid',//A表中有一个集合,里面存放的对象有一个名为roleid的属性

},

operateTime:{

$last:'$operateTime'//取A表操作时间最后一条件数

}

info:{

$first:'$userinfo'//因为数组的扩展,造成了大量的重复数据(只有userrole不同),$first是只取最新的一条

}

}

},

{

$sort:{'operateTime':-1}//操作时间倒序,-1:倒序,1:升序

},

{

$skip:0//跳过几条数据,也就是从第几条数据开始取

},

{

$limit:5//每页显示几条数据

}

]);

java代码整合查询语句

//定义分组字段

String[] groupIds = new String[] {"$userid","$userrole.roleid"};

//定义查询条件

Criteria criteria = new Criteria();

//相当于where username = "zhangsan"

criteria.and("username").is("zhangsan");

//相当于 where age not in("15","20")

criteria.and("age").nin("15","20");

//in操作对应的语句

//criteria.and("").in();

//定义排序条件

Sort sort = new Sort(Direction.DESC,"operateTime");

//联合查询总条数,分页用

Aggregation aggregationCount = Aggregation.newAggregation(

Aggregation.match(criteria);//查询条件

Aggregation.group(groupIds);//分组字段

);

//联合查询条件

Aggregation newAggregation = Aggregation.newAggregation(

Aggregation.lookup('B','userid','userid','userinfo'),//从表名,主表联接字段,从表联接字段,别名

Aggregation.unwind("$userrole"),

Aggregation.match(criteria),

Aggregation.group(groupIds)

.last("$operateTime").as("operateTime")//取值,起别名

.first("$userinfo").as("info"),

Aggregation.sort(sort),

Aggregation.skip(pageSize*(pageNumbhttp://er-1L)),//Long类型的参数

Aggregation.limit(pageSize)

);

//查询

AggregationResults aggregate = mongoTemplate.aggregate(

newAggregation ,"A",BasicDBObject.class//A表,是查询的主表

);

int count = mongoTemplate.aggregate(aggregationCount ,"A",BasicDBObject.class).getMappedResults().size();

//组装分页对象

Page pager = new Page<>(aggregate.getMappedResults(),count,pageSize,pageNumber,page*(pageNumber-1));

//对象转换

将BasicDBObject转换成前面需要的类型.....

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:免费api接口吗(api免费接口)
下一篇:SpringBoot整合flyway实现自动创建表的方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~