【发布时间】:2019-12-03 18:50:40
【问题描述】:
我需要使用 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;
}
}
【问题讨论】:
-
可能是你的组和项目在newAggregation函数中的顺序,重新排序项目和组
-
对不起,缺少投影代码,我会在代码中添加。
-
可以贴出你的样本采集记录,方便我本地执行查看。
-
是的,我在这里发给你
-
{ "_id" : ObjectId("5da9e69ee8222321bc76ac57"), "content" : "Hello Friday", "author" : DBRef("user", ObjectId("5da9e66ce8222321bc76ac56")), "date" : ISODate("2019-10-18T16:21:50.631Z"), "_class" : "com.avenuecode.magpie.domain.Post" }
标签: java spring mongodb aggregation-framework