首页 > 解决方案 > 如何在使用 MongoTemplate 进行分组期间对 mongodb 内部字段求和并推送它

问题描述

我可以在 MongoDB 控制台的推送操作中使用总和。但是,我不知道如何使用 MongoTemplate 做同样的事情?

$group : {
     _id: "$some_id",
     my_field: { $push : {$sum: "$my_field" }}
 }

我为此使用的代码类似于:

Aggregation aggregation =
    Aggregation.newAggregation(
        match(matchingCriteria),
        group("some_id")
            .count()
            .as("count")
            .push("my_field")
            .as("my_field")
        project("some_id", "count", "my_field"));
AggregationResults<MyModel> result =
    mongoTemplate.aggregate(aggregation, "my_collection", MyModel.class);

问题是我想要my_field的总和,但它在这里作为my_field的数组出现(因为我直接使用推送)。我可以在推送操作中使用上述总和来实现相同的目的。但无法将其用于 MongoTemplate。我的应用程序在 Spring Boot 中。我还查看了这些方法的文档,但找不到太多。

另外,我也尝试在字段上直接使用 .sum() (不使用推送),但这对我不起作用,因为 my_field 是一个内部对象,它不是数字,而是分组后的数字数组。这就是为什么我需要使用 push 和 sum 组合。

对此的任何帮助表示赞赏。提前致谢。

标签: javamongodbspring-bootmongotemplate

解决方案


我能够使用以下代码使其工作:

Aggregation aggregation =
    Aggregation.newAggregation(
        match(allTestMatchingCriteria),
        project("some_id")
            .and(AccumulatorOperators.Sum.sumOf("my_field"))
            .as("my_field_sum")
        group("some_id")
            .count()
            .as("count")
            .push("my_field_sum")
            .as("my_field_sum"),
        project("some_id", "count", "my_field_sum"));
AggregationResults<MyModel> result =
    mongoTemplate.aggregate(aggregation, "my_collection", MyModel.class);

我在投影阶段本身使用了AccumulatorOperators.Sum并对内部字段求和并获得所需的输出。然后我将它传递到分组阶段,在那里我进行计数聚合,因为我也需要该数据,然后必须投影生成的所有数据以作为输出收集。


推荐阅读