I tried to convert a String
to Double
with the $convert
operator
...
{
$addFields: {
uslDouble: {
$convert: {
input: "$currentDimension.usl",
to: "double",
one rror: "Impossible to convert str to double",
}
}
},
...
The output error is explicit:
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
My constraint is that I can't upgrade to mongodb > 3.4.14.
Is there any workaround to convert String
to Double
?
CodePudding user response:
That is possible, but I'm not sure about the performance.
The basic idea:
- Split the string into whole and fractional parts
- Convert each part to a number:
o iterate over the characters in each part
o multiply the running total by 10
o add the value of the current digit - Divide the fractional part by 10^(number of digits)
- Add the whole and fractional parts to get the final double
- Remove temporary fields
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
}}
])