Home > database >  MongoDB: merge two columns and convert type
MongoDB: merge two columns and convert type

Time:04-09

Within each document, there are two columns representing, respectively and as strings, whole and decimal numbers of price:

{
"prod_id": "1022"
"whole_price": "10",
"decimal_price": "50"
}
...

How could I perform a merge of those two columns, through an aggregation pipeline, and thus correctly represent the price as a float with a value of 10.5, for each pair of documents?

{
"prod_id": "1022"
"complete_price": 10.5
}
...

CodePudding user response:

You can use $toDouble and $concat in a $project stage to get the desired output:

This query output the field complete_price which is the values concatenated and a "." to create a double value. Then parsed to double to have as a number and not as a string.

db.collection.aggregate([
  {
    "$project": {
      "prod_id": 1,
      "complete_price": {
        "$toDouble": {
          "$concat": [
            "$whole_price",
            ".",
            "$decimal_price"
          ]
        }
      }
    }
  }
])

Example here

Edit:
Also, if your data can not be stable you can use $convert (instead of directly $toDouble) which has onError and onNull like this example

  • Related