MongoDB聚合框架的绝对价值 [英] Absolute value with MongoDB aggregation framework

查看:55
本文介绍了MongoDB聚合框架的绝对价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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 版本开始,您可以使用新的

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聚合框架的绝对价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆