【发布时间】:2020-01-14 13:09:21
【问题描述】:
我正在 springboot 中创建一个新端点,它将返回从 mongo 数据库中的聚合查询生成的用户的简单统计信息。但是我得到了PropertyReferenceException。我已经阅读了多个有关它的 stackoverflow 问题,但没有找到解决此问题的问题。
我们有一个这样的 mongo 数据方案:
{
"_id" : ObjectId("5d795993288c3831c8dffe60"),
"user" : "000001",
"name" : "test",
"attributes" : {
"brand" : "Chrome",
"language" : "English" }
}
数据库中有多个用户,我们希望使用 Springboot 聚合每个 brand 的用户统计信息。 attributes 对象中可以有任意数量的属性。
这是我们正在做的聚合
Aggregation agg = newAggregation(
group("attributes.brand").count().as("number"),
project("number").and("type").previousOperation()
);
AggregationResults<Stats> groupResults
= mongoTemplate.aggregate(agg, Profile.class, Stats.class);
return groupResults.getMappedResults();
这会产生这个有效的 mongo 查询:
> db.collection.aggregate([
{ "$group" : { "_id" : "$attributes.brand" , "number" : { "$sum" : 1}}} ,
{ "$project" : { "number" : 1 , "_id" : 0 , "type" : "$_id"}} ])
{ "number" : 4, "type" : "Chrome" }
{ "number" : 2, "type" : "Firefox" }
但是,当运行一个简单的集成测试时,我们会得到这个错误:
org.springframework.data.mapping.PropertyReferenceException: No property brand found for type String! Traversed path: Profile.attributes.
据我了解,似乎由于attributes 是Map<String, String>,因此可能存在示意图问题。同时我不能修改Profile 对象。
我在聚合中是否遗漏了什么,或者我可以在我的 Stats 对象中更改什么?
作为参考,这里是我们正在使用的数据模型,用于处理 JSON 和 jackson。
Stats 数据模型:
@Document
public class Stats {
@JsonProperty
private String type;
@JsonProperty
private int number;
public Stats() {}
/* ... */
}
Profile 数据模型:
@Document
public class Profiles {
@NotNull
@JsonProperty
private String user;
@NotNull
@JsonProperty
private String name;
@JsonProperty
private Map<String, String> attributes = new HashMap<>();
public Stats() {}
/* ... */
}
【问题讨论】:
标签: java mongodb spring-boot spring-data spring-data-mongodb