【问题标题】:MongoDB: Dividing numbers which are of type stringMongoDB:除以字符串类型的数字
【发布时间】:2020-08-09 06:37:27
【问题描述】:

我想在 MongoDB 中将两个数字相除,但我将它们放在引号中。

我的意思是:

number1: "3"

number2: "25"

我该如何划分它们?引号中的数字是否可以除数?

我试过了:

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

但它不起作用。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    如果你有 MongoDB 版本 > 4.0 - 当你想分割字符串时,你可以使用聚合运算符 $toInt 将它们转换为数字并进行操作:

    db.collection.aggregate([
      /** '$addFields' will add new field to doc, if you just need 'dividedValue' field then use instead '$project' stage(with '_id:0') */
      {
        $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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 2017-03-31
      • 2022-11-27
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多