mongodb 在Mongo中将字符串转换为双精度- 3.4.14

yzxexxkh  于 2023-02-03  发布在  Go
关注(0)|答案(1)|浏览(191)

我尝试使用$convert运算符将String转换为Double

...
       {
        $addFields: {
            uslDouble: {
                $convert: {
                    input: "$currentDimension.usl",
                    to: "double",
                    onError: "Impossible to convert str to double",
                }
            }
        },
        ...

输出错误是明确的:

E QUERY    [thread1] Error: command failed: {
    "ok" : 0,
    "errmsg" : "Unrecognized expression '$convert'",
    "code" : 168,
    "codeName" : "InvalidPipelineOperator"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13

我的限制是我不能升级到mongodb〉3.4.14。
是否有将String转换为Double的解决方法?

umuewwlo

umuewwlo1#

有可能,但我不确定性能如何。
其基本思想是:

  • 将字符串拆分为整数和小数部分
  • 将每个部分转换为数字:

o迭代每个部分中的字符
o将累计值乘以10
o添加当前数字的值

  • 将小数部分除以10^(位数)
  • 将整数部分和小数部分相加得到最后的double
  • 删除临时字段
db.collection.aggregate([
  {$addFields: {
      split: {$split: ["$value", "."]}
  }},
  {$addFields: {
      whole: {"$arrayElemAt": ["$split", 0]},
      fraction: {"$arrayElemAt": ["$split", 1]},
  }},
  {$addFields: {
      whole: {$reduce: {
          input: {$range: [0,{$strLenCP: "$whole"}]},
          initialValue: 0,
          in: {
            $add: [
              {$multiply: ["$$value",10]},
              {"$indexOfArray": [
                    ["0","1","2","3","4","5","6","7","8","9"],
                    {$substr: ["$whole","$$this",1]}
              ]}
            ]
          }
      }},
      fractionVal: {
        $reduce: {
          input: {$range: [0,{$strLenCP: "$fraction"}]},
          initialValue: 0,
          in: {
            $add: [
              {$multiply: ["$$value", 10]},
              {"$indexOfArray": [
                  ["0","1","2","3","4","5","6","7","8","9"],
                  {$substr: ["$fraction","$$this",1]}
              ]}
            ]
          }
        }
      }
  }},
  {$addFields: {
      double: {$add: [
          "$whole",
          {$divide: ["$fractionVal",{"$pow": [10,{$strLenCP: "$fraction"}]}]}
      ]}
  }},
  {$project: {
      fraction: 0,
      fractionVal: 0,
      whole: 0,
      split: 0
  }}
])

Playground

相关问题