java - 如何在使用 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 组合。
对此的任何帮助表示赞赏。提前致谢。
解决方案
我能够使用以下代码使其工作:
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并对内部字段求和并获得所需的输出。然后我将它传递到分组阶段,在那里我进行计数聚合,因为我也需要该数据,然后必须投影生成的所有数据以作为输出收集。
推荐阅读
- javascript - 重定向太多次 - Nodejs
- bash - 如何使用 git bash 中的命令行 Visual Studio 编译器?
- python-3.x - 根据匹配值从字典中返回键
- bash - 如何从每一行中删除连续的重复字符?
- javascript - 查找数组的数量、总和和平均值并将其打印出来
- c - 错误消息说模块中未定义符号“_swap”
- python - 我怎样才能找到重复次数最多的单词以及重复次数
- javascript - Ionic - 在 Android 上切换应用程序时显示启动画面
- docker - 将 WSL 与 /mnt/c windows 卷一起使用时未触发防护
- r - Readxl:处理带有空格的列名