spring数据mongo文档中的计算字段
我有两个非常简单的实体,Post和Comments带有1->*“relation” 以下是我的实体:spring数据mongo文档中的计算字段,spring,mongodb,spring-data-mongodb,Spring,Mongodb,Spring Data Mongodb,我有两个非常简单的实体,Post和Comments带有1->*“relation” 以下是我的实体: @Document @Data @AllArgsConstructor @NoArgsConstructor public class Comment { @Id private String id; @JsonProperty(access = READ_ONLY) @Indexed private String postId; @NotEmpty @Leng
@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;
}
正如你所看到的,我的帖子实体有一个“commentscont”字段,这就是你所认为的。在通过post存储库获取单个post实例/post列表时,是否可以填充此字段?好的,我知道我正在通过评论库对每个帖子的数量进行额外的查询,但对于20篇帖子,我的响应时间从10毫秒增加到了30-40毫秒。通过存储库方法是不可能的。您需要对此进行聚合 差不多
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();
LookupOperation LookupOperation=LookupOperation.newLookup().from(“post”).localField(“_id”).foreignField(“postId”).as(“comments”);
ProjectionOperation ProjectionOperation=项目(“标题”、“说明”、“创建日期”、“更新日期”)和(“注释”).size().as(“注释”);
Aggregation agg=Aggregation.newAggregation(lookupOperation,projectionOperation);
List results=mongoOperations.aggregate(agg,“posts”,Post.class).getMappedResults();