Mongodb $lookup in Spring data mongo

2022-09-04 23:50:58

我是一个新的Mongodb,我对java spring$lookup有问题。

我想在春季数据中使用这个shell

db.NewFeed.aggregate([
    {
        $match : {username : "user001"}
    },
    {
      $lookup:
        {
          from: "NewfeedContent",
          localField: "content.contentId",
          foreignField: "_id",
          as: "NewfeedContent"
        }
   }
])

我在谷歌上找到,但还没有答案。


答案 1

使用春季数据 MongoDB 连接两个集合

员工类别

class Employee {
    private String _id;
    private String name;
    private String dept_id;
}

部门类

class Department {
    private String _id;
    private String dept_name;
}

员工结果类

public class EmpDeptResult {

    private String _id;
    private String name;
    private List<Object> departments;
}

员工服务类

public class EmployeeService {

    @Autowired
    private MongoTemplate mongoTemplate;

    private Logger LOGGER = LoggerFactory.getLogger(EmployeeService.class);

    public void lookupOperation(){
    LookupOperation lookupOperation = LookupOperation.newLookup()
                        .from("Department")
                        .localField("dept_id")
                        .foreignField("_id")
                        .as("departments");

    Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(Criteria.where("_id").is("1")) , lookupOperation);
        List<EmpDeptResult> results = mongoTemplate.aggregate(aggregation, "Employee", EmpDeptResult.class).getMappedResults();
        LOGGER.info("Obj Size " +results.size());
    }
}

答案 2

并非每个“新”功能都能立即将其放入抽象层,例如

因此,您需要做的就是定义一个使用该接口的类,该类将采用直接指定的BSON对象作为其内容:AggregationOperation

public class CustomAggregationOperation implements AggregationOperation {
    private DBObject operation;

    public CustomAggregationOperation (DBObject operation) {
        this.operation = operation;
    }

    @Override
    public DBObject toDBObject(AggregationOperationContext context) {
        return context.getMappedObject(operation);
    }
}

然后,可以在聚合中使用,如下所示:

Aggregation aggregation = newAggregation(
    match(
        Criteria.where("username").is("user001")
    ),
    new CustomAggregationOperation(
        new BasicDBObject(
            "$lookup",
            new BasicDBObject("from", "NewFeedContent")
                .append("localField","content.contentId")
                .append("foreignField", "_id")
                .append("as", "NewFeedContent")
        )
    )
)

其中显示了与内置管道帮助程序混合的自定义类。match()

在每个帮助程序下面发生的所有事情是它们序列化为BSON表示,例如无论如何。因此,这里的构造函数只是直接获取对象,并直接从 返回它,这是接口上的标准方法,在序列化 pipline 内容时将调用该方法。DBObject.toDBObject()