【问题标题】:Calculated field in spring-data-mongo documentspring-data-mongo 文档中的计算字段
【发布时间】:2018-06-16 19:31:04
【问题描述】:

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

这是我的实体:

@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 实体具有您认为的“cmetsCount”字段。在通过帖子存储库获取单个帖子实例/帖子列表时是否可以以某种方式填充此字段?没错,我正在通过评论的存储库对每个 postId 的计数进行额外的查询,而对于 20 个帖子来说,这并不好,我的响应时间从 10 毫秒增加到 30-40 毫秒。

【问题讨论】:

    标签: spring mongodb spring-data-mongodb


    【解决方案1】:

    无法通过存储库方法。您需要为此进行聚合。

    有点像

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 2016-05-15
      • 2020-09-08
      • 1970-01-01
      • 2015-02-19
      • 2011-09-26
      • 2017-09-30
      相关资源
      最近更新 更多