繁体   English   中英

spring-data-mongo文档中的计算字段

[英]Calculated field in spring-data-mongo document

我有两个非常简单的实体,Post和Comments with 1 - > *'relation'。

这是我的实体:

@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;

}

正如您所看到的,我的Post实体具有'commentsCount'字段,这是您认为的。 是否有可能在通过帖子库获取帖子/帖子列表的单个实例时填充此字段? 正确知道我正在通过评论的存储库进行额外的查询以获得每个postId的计数,并且它不适用于20个帖子,我的响应时间从10ms增长到30-40ms。

通过存储库方法无法实现。 你需要聚合这个。

就像是

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM