In my documents, the decimal values are stored as String
( Because of my BigDecimal
in Java converted to String
). This is perfectly OK and required when I am looking one document at a time. However, I require them to be treated as Double
during aggregation purpose (for e.g., $sum
).
Is there a way so that I can covert the String
to Double
during $project
operation (or otherwise) during my aggregation pipeline. So that my successive pipelines will do $sum
on the Double
field.
I am not considering the option of storing them as Double
, as I would need to preserve the precision per document basis, but I am OKif the precision is lost during my aggregation operation.
You can use $toDouble
, which is essentially a short hand for $convert
with to: "double"
Assume we have a document;
{
"str": "3.66"
}
and to convert the string
value to double
;
db.collection.aggregate([
{
$addFields: {
double: {
$toDouble: "$str"
}
}
}
])
will result in;
{
"str": "3.66",
"double": 3.66
}
Where it can be used by other stages of aggregation pipeline.
Check on Mongo Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With