我需要使用 java 和 Mongodb 聚合一些数据。
所以我的 JS 脚本是这样的:
db.post.aggregate([
{$match: {date: {$gte: ISODate("2019-08-28T17:50:09.803Z"), $lte: ISODate("2019-12-03T21:45:51.412+00:00")}}},
{$project: {author: 1, _id: 0}},
{$group: {_id: "$author", count: {$sum:1}}}])
我使用 spring+java 的 Java 代码是:
Aggregation aggregation =
newAggregation(
match(Criteria.where("date")
.lte(dynamicQuery.getEndDate())
.gte(dynamicQuery.getInitDate())),
project("author").andExclude("_id"),
group("author")
.count()
.as("total"));
AggregationResults<Post> result = mongoTemplate.aggregate(aggregation,Post.class, PostSummary.class);
List<Post> map = result.getMappedResults();
我需要按authorId 聚合文档的总和。我的代码返回用户代码,但不返回文档总和。
我们有 2 个系列:
@EqualsAndHashCode(of = "id")
//TODO: Change the @Data to the properly scenario, we don't need
setters in this class anymore.
@Data
@Document (collection = "user")
//TODO: Change collection name to post, because collection are a group
of elements
public class User {
@Id
private String id;
private String name;
private String username;
@Email
private String email;
private String imageUrl;
private String providerId;
private LocalDateTime firstAccess;
}
发布文档:
@Data
@Document(collection = "post")
//TODO: Change collection name to post, because collection are a group of elements
public class Post {
public static final String AUTHOR_FIELD_NAME = "author";
public static final String DATE_FIELD_NAME = "date";
@Id
private String id;
private String content;
@DBRef(lazy = true)
@Field(AUTHOR_FIELD_NAME)
private User author;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
@Field(DATE_FIELD_NAME)
private LocalDateTime date;
public Post(String content, User author, LocalDateTime date) {
this.content = content;
this.author = author;
this.date = date;
}
}
最佳答案
我有一个解决方案,但我不知道这是否是更好的解决方案,所以,我们走吧。
由于 Post Domain 内表示的实体是一个 DBRef,因此 MongoDB 不会将整个 Stringo 解析为 PostSummary.Class
@Getter
@Setter
public class PostSummary {
private User author;
private int count;
}
因此,对于解决方案,我只解析作者中的@Id,并且它有效。因此,如果有人有更好的解决方案,我们现在就有一个解决方案。
应该是这样的:
@Getter
@Setter
public class PostSummary {
@Id
private User author;
private int count;
}
关于java - Mongo 模板在 Spring.Mongodb 中按日期间隔聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59163565/