简体   繁体   中英

Calculated field in spring-data-mongo document

I have two very simple entities, Post and Comments with 1 -> * 'relation'.

here are my entities:

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

}

As you can see my Post entity has the 'commentsCount' field which is what you think it is. Is it somehow possible to populate this field while getting a single instance of post / a list of posts through post repository? Right know I'm doing additional queries through comment's repository for count for each postId and it's not ok as for 20 posts, my response time grew from 10ms to 30-40ms.

Not possible through repository methods. You'll require aggregation for this.

Something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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