Spring Data - MongoDB - 聚合如何投影分组参考文档的所有字段

akc*_*soy 1 mongodb spring-data spring-data-mongodb

我有 2 个文档,主题和评论。每个主题都有很多评论,文档如下所示:

@Document
public class Topic {
    @Id
    private String id;

    @Indexed(unique = true)
    @NotBlank
    private String title;
}


@Document
public class Comment {

    @NotBlank
    private String text;

    @Indexed
    @NotBlank
    private String topic;  // id of topic

    @CreatedDate
    @Indexed
    private LocalDateTime createdDate;
}
Run Code Online (Sandbox Code Playgroud)

所以我实际上将 Topic 的 id 引用保存在评论中。

这是我的聚合场景:列出今天收到最多评论的主题。所以三件事:

  • 获取今天的所有评论(MatchOperation)
  • 按主题分组并汇总评论(GroupOperation)
  • 按总和排序 (SortOperation)

这是到目前为止的代码:

MatchOperation filterCreatedDate = match(Criteria.where("createdDate").gte(today.atStartOfDay()).lt(today.plusDays(1).atStartOfDay()));
GroupOperation groupByTopic = group("topic").count().as("todaysCommentsCount");
SortOperation sortByTodaysCommentsCount = sort(Sort.Direction.DESC, "todaysCommentsCount");

Aggregation aggregation = newAggregation(filterCreatedDate, groupByTopic, sortByTodaysCommentsCount);
AggregationResults<TopTopic> result = mongoTemplate.aggregate(aggregation, Comment.class, TopTopic.class);
Run Code Online (Sandbox Code Playgroud)

这是此输出的特殊类:

public class TopTopic {
    private int todaysCommentsCount;
}
Run Code Online (Sandbox Code Playgroud)

这是我的聚合的输出,其中只有一个主题:

{
    "mappedResults": [
        {
            "todaysCommentsCount": 3
        }
    ],
    "rawResults": {
        "results": [
            {
                "_id": "5dbdca8112a617031728c417",     // topic id
                "todaysCommentsCount": 3
            }
        ],
        "ok": 1.0
    },
    "serverUsed": null,
    "uniqueMappedResult": {
        "todaysCommentsCount": 1
    }
}
Run Code Online (Sandbox Code Playgroud)

我以为我实际上已经非常接近了,但不知怎的,只有当我只有一个主题时它才有效。当来自多个主题的评论应该创建多个组时,我收到此错误:

Could not write JSON: Expected unique result or null, but got more than one!; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Expected unique result or null, but got more than one! (through reference chain: org.springframework.data.mongodb.core.aggregation.AggregationResults[\"uniqueMappedResult\"]
Run Code Online (Sandbox Code Playgroud)

..虽然我不调用任何 getUniqueMappedResult 方法。

我做错了什么?

其次,如何摆脱输出类 TopTopic,并返回用 TodaysCommentsCount 扩展的原始 Topic 值,而不创建特殊的输出类?

我很感激任何帮助。

use*_*814 5

第一部分

您将返回AggregationResults给调用者,其中 jackson 正在序列化为 json 并在调用时失败getUniqueMappedResult

添加主题字段_idTopTopic并读取映射结果AggregationResults

List<TopTopic> topTopics = result.getMappedResults()
Run Code Online (Sandbox Code Playgroud)

你的输出看起来像

 [
    {
       "_id": "5dbdca8112a617031728c417",
       "todaysCommentsCount": 3
    }
 ]
Run Code Online (Sandbox Code Playgroud)

第二部分

您可以使用$$ROOT变量 with$first来映射阶段中的整个文档$group,然后$replaceRoot提升合并文档($mergeObjects合并docand todaysCommentCount)。

添加todaysCommentsCount到 Topic 类。

就像是

MatchOperation filterCreatedDate = match(Criteria.where("createdDate").gte(today.atStartOfDay()).lt(today.plusDays(1).atStartOfDay()));
GroupOperation groupByTopic = group("topic").first("$$ROOT").as("doc").count().as("todaysCommentsCount");
SortOperation sortByTodaysCommentsCount = sort(Sort.Direction.DESC, "todaysCommentsCount");
ReplaceRootOperation replaceRoot = Aggregation.replaceRoot().withValueOf(ObjectOperators.valueOf("doc").mergeWith(new Document("todaysCommentsCount", "$todaysCommentsCount")));

Aggregation aggregation = newAggregation(filterCreatedDate, groupByTopic, sortByTodaysCommentsCount, replaceRoot);
AggregationResults<TopTopic> result = mongoTemplate.aggregate(aggregation, Comment.class, Topic.class);

List<Topic> topTopics = result.getMappedResults();
Run Code Online (Sandbox Code Playgroud)

你的输出看起来像

 [
    {
       "_id": "5dbdca8112a617031728c417",
       "title" : "topic",
       "todaysCommentsCount": 3
    }
 ]
Run Code Online (Sandbox Code Playgroud)

更新(添加 $lookup 阶段以拉入主题字段)

MatchOperation filterCreatedDate = match(Criteria.where("createdDate").gte(today.atStartOfDay()).lt(today.plusDays(1).atStartOfDay()));
GroupOperation groupByTopic = group("topic").count().as("todaysCommentsCount");
SortOperation sortByTodaysCommentsCount = sort(Sort.Direction.DESC, "todaysCommentsCount");
LookupOperation lookupOperation = LookupOperation.newLookup().
                                    from("topic").
                                    localField("_id").
                                    foreignField("_id").
                                    as("topic");
ReplaceRootOperation replaceRoot = Aggregation.replaceRoot().withValueOf(ObjectOperators.valueOf("todaysCommentsCount").mergeWithValuesOf(ArrayOperators.arrayOf("topic").elementAt(0)));

Aggregation aggregation = newAggregation(filterCreatedDate, groupByTopic, sortByTodaysCommentsCount, lookupOperation, replaceRoot);
AggregationResults<TopTopic> result = mongoTemplate.aggregate(aggregation, Comment.class, Topic.class);

List<Topic> topTopics = result.getMappedResults();
Run Code Online (Sandbox Code Playgroud)