问题描述
我正在使用MongoDB聚合框架,并且需要取一个金额字段的绝对值,我在项目部分和组部分中都使用了该值,例如:
I'm using the MongoDB aggregation framework and need to take the absolute value of an amount field, which I use in both the project portion and the group portion, ex:
'$project' => {
'amount' => 1,
'_id' => 0
}
....
'$group' => {
'total' => {'$sum' => '$amount'}
}
在这种情况下,如何获取金额"字段的绝对值?我无法在文档中找到它(也许它不可用?)
How do you take the absolute value of the 'amount' field in this case? I wasn't able to find it in the docs (maybe it's not available?)
推荐答案
它不是直接可用的,但是您可以使用$cond
运算符和$subtract
在$project
中使用$subtract
来做到这一点(作为JavaScript对象) ):
It's not directly available, but you can do it using a $cond
operator and a $subtract
within a $project
like this (as a JavaScript object):
{ $project: {
amount: {
$cond: [
{ $lt: ['$amount', 0] },
{ $subtract: [0, '$amount'] },
'$amount'
]
}}}
因此,如果使用amount < 0
,则使用0 - amount
,否则直接使用amount
.
So if amount < 0
, then 0 - amount
is used, otherwise amount
is used directly.
更新
从MongoDB的 3.2 版本开始,您可以使用新的 $abs
聚合表达式运算符可直接执行此操作:
As of the 3.2 release of MongoDB, you can use the new $abs
aggregation expression operator to do this directly:
{ $project: { amount: { $abs: '$amount' } }
这篇关于MongoDB聚合框架的绝对价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!