查询主表ChatRoom,从表Friend。
方法一:
第一次查询连表查询:
主表ChatRoom中字段owner与从表Friend中的字段toUser关联 LookupOperation lookup = Aggregation.lookup("Friend", ChatRoom.Fields.owner, Friend.Fields.toUser, "FriendChatRoom1");
生成虚表FriendChatRoom1。
第二次查询连表查询:
主表ChatRoom中字段owner与从表Friend中的字段fromUser关联 LookupOperation lookup1 = Aggregation.lookup("Friend", ChatRoom.Fields.owner, Friend.Fields.fromUser, "FriendChatRoom2");
生成虚表FriendChatRoom2
//筛选条件 Criteria criteria = new Criteria().orOperator( 第一张虚表筛选条件 Criteria.where("FriendChatRoom1.fromUser").is(user.getId()), 第二张虚表筛选条件 Criteria.where("FriendChatRoom2.toUser").is(user.getId()) ); 主表筛选条件 criteria.and(ChatRoom.Fields.enable).is(true); MatchOperation match = Aggregation.match(criteria); 分页 AggregationOperation operationNumber = Aggregation.skip((req.getPageNumber()) * req.getPageSize()); AggregationOperation operationSize = Aggregation.limit(req.getPageSize()); 将所有条件顺序放入Aggregation开始查询 Aggregation aggregation = Aggregation.newAggregation(lookup,lookup1,match,operationNumber,operationSize);
public List<ChatRoom> findAllEnableByFriend(User user, RoomFriendsRequest req){
//连表生成虚表1
LookupOperation lookup = Aggregation.lookup("Friend", ChatRoom.Fields.owner, Friend.Fields.toUser,
"FriendChatRoom1");
//连表生成虚表2
LookupOperation lookup1 = Aggregation.lookup("Friend", ChatRoom.Fields.owner, Friend.Fields.fromUser,
"FriendChatRoom2");
//筛选条件
Criteria criteria = new Criteria().orOperator(
Criteria.where("FriendChatRoom1.fromUser").is(user.getId()),
Criteria.where("FriendChatRoom2.toUser").is(user.getId())
);
criteria.and(ChatRoom.Fields.enable).is(true);
MatchOperation match = Aggregation.match(criteria);
//分页
AggregationOperation operationNumber = Aggregation.skip((req.getPageNumber()) * req.getPageSize());
AggregationOperation operationSize = Aggregation.limit(req.getPageSize());
//查询
Aggregation aggregation = Aggregation.newAggregation(lookup,lookup1,match,operationNumber,operationSize);
AggregationResults<ChatRoom> results = mMongoTemplate.aggregate(aggregation, "ChatRoom", ChatRoom.class);
return results.getMappedResults();
}
方法二:
MongoRepository使用in来查询两张表
1. 查询出从表的Id集合,再查主表中符合条件的在从表的Id集合中
public List<String> findAllToUserByFromUser(String fromId) {
Query query = Query.query(
Criteria.where(Follow.Fields.fromUser).is(fromId)
);
query.fields().include(Follow.Fields.toUser);
DistinctIterable<String> distinctIds = mMongoTemplate.getCollection(mMongoTemplate.getCollectionName(Follow.class))
.distinct(Follow.Fields.toUser, query.getQueryObject(), String.class);
return Lists.newArrayList(distinctIds);
}
public Page<ChatRoom> findAllEnableByFollow(RoomFriendsRequest req,List<String> followUserIds){
PageRequest pageRequest = PageRequest.of(req.getPageNumber(), req.getPageSize(), Sort.Direction.DESC, ChatRoom.Fields.viewPerson);
Page<ChatRoom> list = mChatRoomRepository.findByOwnerInAndEnable(followUserIds,true,pageRequest);
return list;
}