簡體   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