Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

mongodb - Can't coerce out of range value with mongo aggregator

I'm trying to use the aggregate but encounters a problem with a large number.

Schema

amount: Number

Input data when inserting

{ type: "Deposit", amount: 10000000000000000000000 },
{ type: "Withdraw", amount: 50000000000000000000000 },

stored as

{ type: "Deposit", amount: 1e+22 }
{ type: "Withdraw", amount: 5e+22 }

Next, I try to use the aggregator to match both types and convert withdraw amount to negative by multiplying by -1

[
  {
    '$match': {
      '$or': [
        {
          'event': 'Deposit'
        }, {
          'event': 'Withdraw'
        }
      ]
    }
  }, {
    '$project': {
      'event': '$event', 
      'amount': {
        '$cond': {
          'if': {
            '$eq': [
              '$event', 'Deposit'
            ]
          }, 
          'then': '$amount', 
          'else': {
            '$multiply': ['$amount', -1]
          }
        }
      }
    }
  }
]

However, the problem Can't coerce out of range value 1e+22 to long. My question is, is there any other way to accomplish this with the aggregator or should I store the data different way to prevent it to become ...e+... when the number exceeds the range.

I'm currently using MongoDB v4.4.3


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a resolved bug SERVER-42756 in MongoDB specific versions, I am not sure how it was affect,

You should try mongoose Decimal128 type,

Schema:

amount: mongoose.Types.Decimal128

Second option: if you don't want to change type in your schema try, $toDecimal operator from MongoDB v4.0,

'$multiply': [{ $toDecimal: '$amount' }, -1]

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...