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

时间:2018-01-07 17:36:47

标签: spring mongodb spring-data-mongodb

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

这是我的实体:

@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个帖子,我的响应时间从10毫秒增加到30-40毫秒。

1 个答案:

答案 0 :(得分: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();