【问题标题】:Spring Data Mongo - Custom AggregtionOption not workingSpring Data Mongodb - 自定义聚合选项不起作用
【发布时间】:2020-07-27 03:01:54
【问题描述】:

我尝试基于https://github.com/krishnaiitd/learningJava/tree/master/spring-boot-sample-data-mongodb 创建自定义聚合操作 当我在聚合中使用自定义聚合进行查找时,它抛出了一个异常,指出在实体上找不到“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!

【问题讨论】:

    标签: mongodb spring-data-mongodb spring-mongodb


    【解决方案1】:

    TypedAggregation 是一个特殊的聚合,它保存输入聚合类型的信息。

    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();
    

    【讨论】:

    • 谢谢@Valijon。做出您建议的更改后,我能够获得聚合结果。但是,我现在在使用字符串创建的小组赛阶段面临一个新问题。它说 ID 字段应该是一个累加器对象。
    • @Farhan 这很正常。请发布您的小组赛阶段。正常情况下应该是……group(...).sum|.addToSet|.first(...).as("fieldname")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多