Spring 数据 Mongo - 自定义聚合选项不工作

Spring Data Mongo - Custom AggregtionOption not working

我尝试基于 https://github.com/krishnaiitd/learningJava/tree/master/spring-boot-sample-data-mongodb 创建自定义 AggregationOperation 当我在我的聚合中使用自定义聚合进行查找时,它抛出了一个异常,指出在实体上找不到 "as" 字段。

如果有人尝试使用自定义 AggregationOperation,请分享您的代码或让我知道哪里出错了。

下面是我的代码,

String lookup = "{ $lookup : { from: 'ITEM', localField : 'item_id', foreignField : '_id', as : 'item' } }";
TypedAggregation<Order> aggregation = Aggregation.newAggregation(Order.class, 
        new CustomAggregationOperation(lookup),
        unwind("item", false));

异常:

org.springframework.data.mapping.PropertyReferenceException: No property item found for type Order!

A TypedAggregation is a special Aggregation that holds information of the input aggregation type.

https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/aggregation/TypedAggregation.html

这意味着 Spring 将在每个阶段后验证您的文档没有更改结构。

由于您正在尝试转换原始文档,因此您需要使用标准 Aggregation

Aggregation aggregation = Aggregation.newAggregation(
    new CustomAggregationOperation(lookup),
    unwind("item", false)
);

List<Order> result = mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(Order.class), Order.class).getMappedResults();