You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中实现MongoDB聚合$lookup的Pipeline查询?

在Java中实现带Pipeline条件的MongoDB $lookup聚合查询

你需要实现的MongoDB原生带Pipeline的$lookup查询如下:

{
  from: "profile_recommendation_info",
  localField: "_id",
  foreignField: "profile_id",
  as: "result",
  pipeline : [
    {
      $match : {
        "new_recommendations" : {
          $eq : null
        }
      }
    }
  ]
}

对应的Java实现可以通过MongoDB驱动的LookupOperation结合聚合管道完成,具体代码如下:

  1. 先构建$lookup内部的$match管道阶段:
// 构建匹配new_recommendations为null的条件
MatchOperation matchStage = Aggregation.match(Criteria.where("new_recommendations").is(null));
  1. 创建带Pipeline的LookupOperation实例:
LookupOperation lookupWithPipeline = LookupOperation.from(CommonConstants.PROFILE_RECOMMENDATION_INFO)
        .localField(CommonConstants.ID)
        .foreignField(CommonConstants.PROFILE_UNDERSCORE_ID)
        .as(CommonConstants.RESULT)
        .pipeline(Arrays.asList(matchStage));
  1. 将该查询加入聚合管道并执行:
Aggregation aggregation = Aggregation.newAggregation(lookupWithPipeline);
// 替换为你的集合名和结果实体类
AggregationResults<YourTargetEntity> results = mongoTemplate.aggregate(aggregation, "your_source_collection", YourTargetEntity.class);

代码对应说明

  • from()对应原生查询的from字段,指定关联集合名
  • localField()和foreignField()分别对应原生的localField、foreignField,设置关联匹配字段
  • as()对应原生的as,定义查询结果的别名
  • pipeline()传入构建好的管道阶段列表,和原生查询中的pipeline数组完全对应

内容的提问来源于stack exchange,提问作者Sanjay Naik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:54:51