MongodbTemplate $lookup使用

$lookup

#######做连表查询,相当于mysql的left outer join

mongodbTemplate使用过程中注意事项

#######关联表如果A,B表中的关联字段为string类型和ObjectId类型,注意加上一下代码,否则关联不生效

AddFieldsOperation addFieldsOperation =
                AddFieldsOperation.addField("feedId")
.withValue(ConvertOperators.ToObjectId.toObjectId("$feedId"))
.build();

#######参考实例如下

 String userId = "111112222";
        long lastTime = 1653562624259L;
        long limit = 3L;
       /* LookupOperation lookupOperation = LookupOperation.newLookup()
                .from("bbs_feed")//关联表名
                .localField(ReflectionUtil.getFieldName(Inbox::getFeedId))//主表关联字段
                .foreignField(ReflectionUtil.getFieldName(Feed::getId))//次表关联字段
                .as("feedTemp");//临时集合别名*/
        String tableAlias = "feedList";
        Criteria criteriaInbox = Criteria
                .where(ReflectionUtil.getFieldName(Inbox::getType)).is(BizTypeEnum.FEED.getType())
                .and(ReflectionUtil.getFieldName(Inbox::getUserId)).is(userId);

//        criteriaInbox.and(ReflectionUtil.getFieldName(Inbox::getPublishTime)).lt(lastTime);

        MatchOperation matchInbox = Aggregation.match(criteriaInbox);
        LimitOperation limitInbox = Aggregation.limit(limit);

        LookupOperation lookupOperation =
                Aggregation.lookup(Constants.BBS_FEED, ReflectionUtil.getFieldName(Inbox::getFeedId)
                        , "_" + ReflectionUtil.getFieldName(Feed::getId),
                        tableAlias);

        String feedConditionLevel = tableAlias.concat(".").concat(ReflectionUtil.getFieldName(Feed::getLevel));
        String feedConditionDeleteFlag = tableAlias.concat(".").concat(ReflectionUtil.getFieldName(Feed::getDeleteFlag));
        Criteria criteria2Foreign = Criteria.where(feedConditionLevel).ne(FeedLevelEnum.LOW.getValue())
                .and(feedConditionDeleteFlag).is(BooleanEnum.NO.getValue());

        MatchOperation matchFeed = Aggregation.match(criteria2Foreign);

        AddFieldsOperation addFieldsOperation =
                AddFieldsOperation.addField("feedId").withValue(ConvertOperators.ToObjectId.toObjectId("$feedId")).build();
        SortOperation sort = Aggregation.sort(Sort.Direction.DESC, ReflectionUtil.getFieldName(Inbox::getPublishTime));

        Aggregation aggregation = Aggregation.newAggregation(matchInbox, addFieldsOperation
                , lookupOperation, matchFeed, sort, limitInbox);


        AggregationResults inboxAggration = mongoTemplate.aggregate(aggregation, Inbox.class, InboxFeedAggration.class);
        List inboxResults = inboxAggration.getMappedResults();
        System.out.println("inboxResults=" + inboxResults.size() + "====" + JSON.toJSONString(inboxResults));

你可能感兴趣的:(MongodbTemplate $lookup使用)