Absolute value with MongoDB aggregation framework

回眸只為那壹抹淺笑 提交于 2019-12-29 08:33:09

问题


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?)


回答1:


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'
    ]
}}}

So if amount < 0, then 0 - amount is used, otherwise amount is used directly.

UPDATE

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' } }


来源:https://stackoverflow.com/questions/17561804/absolute-value-with-mongodb-aggregation-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!