在mongodb中如何将十六进制字符串转换为数字? [英] How do you convert a hexadecimal string into a number in mongodb?

查看:122
本文介绍了在mongodb中如何将十六进制字符串转换为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含如下字符串的集合:

I have a collection that has strings such as this:

left_eye_val : "0x0", right_eye_val : "0x2"

我正在设置一些派生字段作为聚合管道的一部分,该管道在其第一阶段必须将十六进制字符串0x0"、0x2"成数字.

I'm setting up some derivative fields as part of a aggregation pipeline which at its first stage must convert the hexadecimal strings "0x0", "0x2" into numbers.

我试过的运算符:{$toInt:"$left_eye_val"} 返回 $convert 中非法的十六进制输入,onError 值:0x0

The operator I tried: {$toInt:"$left_eye_val"} returns Illegal hexadecimal input in $convert with onError value:0x0

有没有办法使用内置的 mongodb 运算符将这些字符串转换为数字?如果没有,有哪些方法可以实现这一目标?

Is there a way to convert these strings into numbers using built-in mongodb operators? If not, what are some of the ways one might accomplish this?

推荐答案

@Domscheit 的回答在十六进制字符串不包含前面的 '0x' 时有效;如果是,则修改@Domscheit 发布的函数如下:

@Domscheit's answer works if the hexadecimal string does not contain the '0x' in front of it; if it does, then modify the function posted by @Domscheit as follows:

function baseToDecimal(input, base) {
   // works up to 72057594037927928 / FFFFFFFFFFFFF8
   var field = input;
   return {
      $sum: {
         $map: {
            input: { $range: [0, { $strLenBytes: field }] },
            in: {
               $multiply: [
                  { $pow: [base, { $subtract: [{ $strLenBytes: field }, { $add: ["$$this", 1] }] }] },
                  { $indexOfBytes: ["0123456789ABCDEF", { $toUpper: { $substrBytes: [field, "$$this", 1] } }] }
               ]
            }
         }
      }
   };
}

并按如下方式调用它,使用replaceOne函数删除x

and call it as follows, using the replaceOne function to remove the x

db.collection.aggregate([{$set:{lHex: {$replaceOne: {input:"$hex", find:"x", replacement: "0"}}}}, {$set: {decimal: baseToDecimal("$lHex", 16)}}])

这篇关于在mongodb中如何将十六进制字符串转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆