Absolute value with MongoDB aggregation framework

后端 未结 1 1076
醉梦人生
醉梦人生 2020-12-20 17:24

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:

相关标签:
1条回答
  • 2020-12-20 17:46

    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' } }
    
    0 讨论(0)
提交回复
热议问题