MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come si converte una stringa esadecimale in un numero in mongodb?

Tale funzione non esiste ancora, vedi Supporta la conversione di base in $convert

Puoi definire funzioni come questa:

function decimalToBase(input, base) {
   // works up to 72057594037927928 / FFFFFFFFFFFFF8
   var field = "$" + input;
   return {
      $let: {
         vars: {
            bits: {
               $reduce: {
                  input: { $range: [0, 56] },
                  initialValue: [{ dec: field }],
                  in: {
                     $cond: {
                        if: { $gt: [{ $last: "$$value.dec" }, 0] },
                        then: {
                           $concatArrays: ["$$value",
                              [{
                                 b: { $substrBytes: ["0123456789ABCDEF", { $mod: [{ $last: "$$value.dec" }, base] }, 1] },
                                 dec: { $trunc: { $divide: [{ $last: "$$value.dec" }, base] } }
                              }]
                           ]
                        },
                        else: "$$value"
                     }
                  }
               }
            }
         },
         in: {
            $reduce: {
               input: { $reverseArray: "$$bits.b" },
               initialValue: "",
               in: { $concat: ["$$value", "$$this"] }
            }
         }
      }
   }
};

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] } }] }
               ]
            }
         }
      }
   };
}

e poi usalo, ad esempio in questo modo:

db.collection.insertOne({ hex: "A3F" })
db.collection.aggregate({ $set: { decimal: baseToDecimal("hex", 16)} })