I have a collection that has strings such as this:
left_eye_val : "0x0", right_eye_val : "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.
The operator I tried:
{$toInt:"$left_eye_val"}
returns Illegal hexadecimal input in $convert with onError value:0x0
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'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] } }] }
]
}
}
}
};
}
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)}}])