我使用Spring Data MongoDB生成聚合查询。有一次,我这样做:
// 5. Rejoin the array with group.
group("email", "name", "surname", "birthday", "creationTime", "updateTime", "technology")
.push(SCORES_FIELD).as(SCORES_FIELD));
生成的步骤(在日志中)是:
"$group" : {
"_id" : {
"email" : "$_id",
"name" : "$name" ,
"surname" : "$surname" ,
"birthday" : "$birthday" ,
"creationTime" : "$creationTime" ,
"updateTime" : "$updateTime" ,
"technology" : "$technology"
} ,
"scores" : { "$push" : "$scores"}
}
哪个非常好,我已经在Mongo shell上对它进行了测试,并准确回馈了我想要的内容。
问题在于,当我对Spring Data执行相同操作时,电子邮件字段(Mongo中的_id字段)被映射为null。我的地图可能有些不对劲,但我还没有弄清楚到底是什么。这是模特:
@Document(collection = "user")
public class User implements UserDetails {
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private LocalDate birthday;
@Id
@Field("_id")
private String email;
private Collection<? extends GrantedAuthority> authorities;
private String password;
private Set<Score> scores;
private LocalDateTime creationTime;
private LocalDateTime updateTime;
private String technology;
// Getters and setters, hashmap, equals and toString
}
我已经完成了其他查询,一切都很完美。我只在这个问题上遇到这个问题,这是我唯一的聚合。
答案 0 :(得分:2)
宣传我的评论以回答。
_id无法映射到电子邮件,因为组级会在_id文档中返回多个键。 previousOperation()
只是从以前的组操作返回_id的便捷方法。您可以尝试更改为group("email").first("name").as("name")....
,看看是否有帮助。
我希望spring能够从模型中读取Field注释,并将_id字段映射回电子邮件。