1.描述
想要通过group 聚合操作 统计总钱数 其中总钱数需要将其中两个字段进行相加处理
使用命令行语句例子如下
db.sales.aggregate(
[
{ $project: { item: 1, total: { $add: [ "$price", "$fee" ] } } }
]
)
2.java对应代码
GroupOperation groupOperation = Aggregation.group("xxx").sum("a").as("aa").sum("b").as("bb");
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),
groupOperation,
//这里为对应相加字段并生成新字段的处理
Aggregation.project("aa").andExpression("add('$aa','$bb')").as("cc")
);
结果为 Document{{_id=null, aa=469407.0, cc=938775.0}}
官网相关地址
https://docs.mongodb.com/manual/reference/operator/aggregation/add/index.html
本文介绍如何在MongoDB中使用聚合框架来实现对多个字段求和的操作,并提供了具体的命令行语句及Java代码示例。
2万+

被折叠的 条评论
为什么被折叠?



