[英]Calculated field in spring-data-mongo document
I have two very simple entities, Post and Comments with 1 -> * 'relation'. 我有两个非常简单的实体,Post和Comments with 1 - > *'relation'。
here are my entities: 这是我的实体:
@Document
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Comment {
@Id
private String id;
@JsonProperty(access = READ_ONLY)
@Indexed
private String postId;
@NotEmpty
@Length(max = 300)
private String description;
@JsonProperty(access = READ_ONLY)
private Instant createdDate;
}
@Document
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Post {
@Id
@JsonProperty(access = READ_ONLY)
private String id;
@NotEmpty
@Length(max = 300)
private String title;
@NotEmpty
private String description;
@JsonProperty(access = READ_ONLY)
private Instant createdDate;
@JsonProperty(access = READ_ONLY)
private Instant updatedDate;
@JsonProperty(access = READ_ONLY)
private Long commentsCount = 0L;
}
As you can see my Post entity has the 'commentsCount' field which is what you think it is. 正如您所看到的,我的Post实体具有'commentsCount'字段,这是您认为的。 Is it somehow possible to populate this field while getting a single instance of post / a list of posts through post repository? 是否有可能在通过帖子库获取帖子/帖子列表的单个实例时填充此字段? Right know I'm doing additional queries through comment's repository for count for each postId and it's not ok as for 20 posts, my response time grew from 10ms to 30-40ms. 正确知道我正在通过评论的存储库进行额外的查询以获得每个postId的计数,并且它不适用于20个帖子,我的响应时间从10ms增长到30-40ms。
Not possible through repository methods. 通过存储库方法无法实现。 You'll require aggregation for this. 你需要聚合这个。
Something like 就像是
LookupOperation lookupOperation = LookupOperation.newLookup().from("post").localField("_id").foreignField("postId").as("comments");
ProjectionOperation projectionOperation = project("title", "description", "createdDate", "updatedDate").and("comments").size().as("commentsCount");
Aggregation agg = Aggregation.newAggregation(lookupOperation, projectionOperation);
List<Post> results = mongoOperations.aggregate(agg, "posts", Post.class).getMappedResults();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.