Spring data mongo:当路径包含HashMap的键时,投影不起作用 [英] Spring data mongo: Projection not working when path includes a key of a HashMap

查看:39
本文介绍了Spring data mongo:当路径包含HashMap的键时,投影不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

当我尝试投影一个位于java.util.Map内的值时,我得到以下异常。但是,当我在bot Mongo中运行生成的外壳查询时,它就可以工作了。如果有人能指出这个问题,我将不胜感激。

org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property Germany found on com.nntn.corona.snapshot.repo.model.StatWithDelta!

在Java中查询代码

春靴家长:2.0.5.RELEASE

Criteria matchCriteria = Criteria.where("timestamp").gte(startDate);
        MatchOperation match = Aggregation.match(matchCriteria);
        SortOperation sort = sort(new Sort(Sort.Direction.ASC, "timestamp"));

        // @formatter:off
        ProjectionOperation projection = project()
                .andExpression("timestamp").as("timestamp")
                .andExpression("countries.germany.total").as("total")
                .andExpression("countries.germany.today").as("today");
        // @formatter:on

        Aggregation aggregation = newAggregation(match, sort,projection);

        AggregationResults<Document> result = mongoTemplate.aggregate(aggregation, SnapshotEntry.class,
                Document.class);
        return result.getMappedResults();

数据模型

Java表示

@Document(collection = "snpashots")
public class SnapshotEntry {

    @Id
    private String id;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    @Temporal(TemporalType.TIMESTAMP)
    private DateTime timestamp;

    private Map<String, StatWithDelta> countries;
    private StatEntity total;
    private StatEntity today;
    private String source;
    private String previousRecordId;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class StatWithDelta {
        private StatEntity total;
        private StatEntity today;
    }

}

Json表示

{
    "_id" : "21-03-2020",
    "timestamp" : ISODate("2020-03-21T09:26:00.965Z"),
    "countries" : {
        "germany" : {
            "total" : {
                "born" : NumberLong(81008),
                "dead" : NumberLong(3255),
                "sick" : NumberLong(30000)
            },
            "today" : {
                "born" : NumberLong(50),
                "dead" : NumberLong(10),
                "sick" : NumberLong(12)
            }
        }
    },
    "_class" : "com.nntn.snapshot.repo.model.SnapshotEntry"
}

推荐答案

问题在TypedAggregation。这是一种特殊的聚合,Spring在其中保存输入聚合类型的信息。

要避免这种情况,请使用原始聚合(就像在MongoDB外壳中运行一样):

AggregationResults<SnapshotEntry> result = mongoTemplate.aggregate(aggregation, 
            mongoTemplate.getCollectionName(SnapshotEntry.class),
            SnapshotEntry.class);

这篇关于Spring data mongo:当路径包含HashMap的键时,投影不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆