这期内容当中小编将会给大家带来有关怎么在java中使用mongodb实现多表联查,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
多表联查的查询语句:
此处使用的为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*(pageNumber-1L)),//Long类型的参数
Aggregation.limit(pageSize)
);
//查询
AggregationResults<BasicDBObject> aggregate = mongoTemplate.aggregate(
newAggregation ,"A",BasicDBObject.class//A表,是查询的主表
);
int count = mongoTemplate.aggregate(aggregationCount ,"A",BasicDBObject.class).getMappedResults().size();
//组装分页对象
Page<BasicDBObject> pager = new Page<>(aggregate.getMappedResults(),count,pageSize,pageNumber,page*(pageNumber-1));
//对象转换
将BasicDBObject转换成前面需要的类型.....
上述就是小编为大家分享的怎么在java中使用mongodb实现多表联查了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。