Convert string to number

I need to do this
db.statistics1.find().forEach( function (d) {
d.Active= parseInt(d.Active);
db.statistics1.save(d);
});
but the name of files is Tax Rate, yes, a blank space in the middle of the name
I’ve a export json file. All fields in document are string
I need to convert some fields into integer and float
Thnaks

1 Like

Hello.

You can post a sample document with the fields you are facing problems with.

If you have a field with spaces like tax rate, refer it by surrounding with quotes (can use single or double quotes). For example,

db.collection.find( { "tax rate": 8 } )

Also, see this topic in the MongoDB Manual: Document - Field Names.

1 Like

Hi, thanks
The find function works fine. This is not the problem
The problem is this script
db.statistics1.find().forEach( function (d) {
d.“Tax Rate”= parseFloat(d.“Tax Rate”);
db.statistics1.save(d);
});
does not work. I need to access to value of “Tax Rate” element in order to change it from string to float/numeric
Thanks

1 Like

@Felipe_Fernandez, you can do this:

db.test.find()
       .forEach(d => { 
                       d['tax rate'] = parseFloat(d['tax rate']); 
                       db.test.save(d); 
})
1 Like

Works!. Thanks a lot

Note that you don’t need to modify the documents in the shell, you can use $toDouble (or any other conversion function) in update command to modify the field.

Example:

     db.test.update({}, [ {$set:{ "tax rate" : {$toDouble: "$tax rate"}}} ], {multi:true})

will do the same thing your script is doing without bringing documents to the client and without potential race conditions. You can use $toInt, $toLong or $convert if you want to specify more options.

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.