Spring数据mongo:当路径包含HashMap的键时,投影不起作用



问题

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

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 shell中运行一样(:

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

最新更新