MongoDB:用引号引起来的除号“”

问题描述 投票:0回答:2

我想在MongoDB中将两个数字相除,但我用引号将它们括起来。

我的意思是:

数字1:“ 3”

number2:“ 25”。

我如何划分它们?用引号引起来的数字除数有可能吗?

我尝试过:

db.myproject.find({ $divide: [ "number1", "number2" ] })

但不起作用。

mongodb division divide quotation-marks
2个回答
0
投票

var num =(number1 / number2)>> 0;


0
投票

如果您使用的是MongoDB版本> 4.0-当您想分割字符串时,可以使用聚合运算符$toInt将其转换为数字并执行操作:

db.collection.aggregate([
  /** '$addFields' will a new field to doc, if you just need 'dividedValue' field then use instead '$project' stage */
  {
    $addFields: {
      dividedValue: {
        $cond: [
          { $eq: [ "$number2", "0" ]}, // When you divide by 0, '$divide' result in error so we're having conditional error check here
          "Can't divide by Zero",
          {
            $divide: [
              {
                $toInt: "$number1"
              },
              {
                $toInt: "$number2"
              }
            ]
          }
        ]
      }
    }
  }
])

测试: mongoplayground

© www.soinside.com 2019 - 2024. All rights reserved.