Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB String to Double conversion during aggregation pipeline

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.

like image 900
Poorna Subhash Avatar asked Apr 28 '14 11:04

Poorna Subhash


1 Answers

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

like image 190
buræquete Avatar answered Oct 29 '22 12:10

buræquete