jsonmongodbtype-conversion

MongoDB, Convert a string with commas to double in $convert(aggregation). Failed to parse number '1,533.07'


I need convert to double any string (if it is valid), but string with commas break my query.

I have a Documents like this:

{ 
  'city': 'Stormwind',
  'sales': '256.03'
},
{ 
  'city': 'Gilneas',
  'sales': '100'
},
{ 
  'city': 'Orgrimmar',
  'sales': '1,856.60'
},
{ 
  'city': 'Dalaran',
  'sales': '8,566,586.41'
}

My query is:

db.projects.aggregate([
{
        $project: {
            city: 1,
            sales: {
                '$convert': { 'input': '$sales', 'to': 'double', onError: 0 }
            }
        }
    }
]

The result is:

{ 
  'city': 'Stormwind',
  'sales': 256.03
},
{ 
  'city': 'Gilneas',
  'sales': 100
},
{ 
  'city': 'Orgrimmar',
  'sales': 0
},
{ 
  'city': 'Dalaran',
  'sales': 0
}

The problem is the comma in the sales: '1,856.60' and '8,566,586.41'.

I need convert to Double those values, but onError fires when there are commas in the string.


Solution

  • I don't see any options for $convert addressing the issue of commas being present, so MongoDB probably assumes a purely numeric string value. We can most likely get around this limitation by stripping out the commas prior to converting. I don't see any operators for removing these directly, but we should be able to use $split, $concat, and $reduce to achieve the same result.

    Something like this should work:

    db.test.aggregate([
        { $project: {
            data: {
                $convert: {
                    input: {
                        $reduce: {
                            input: {
                                $split: ['$data', ',']
                            },
                            initialValue: '',
                            in: {
                                $concat: ['$$value', '$$this']
                            }
                        }
                    },
                    to: 'double',
                    onError: 0
                }
            }
        }}
    ])