Mongodb – Mongo: how to covert a string to decimal

decimalmongodbtype conversion

I have written millions of documents with $CURRENT_CASH_BALANCE as strings instead of decimals. How can I convert them all to decimals?

Best Answer

Consider a collection with documents:

{ _id: 1, bal: "123.45" }
{ _id: 2, bal: "67890"}
{ _id: 3, bal: 999 }

The following command can be run from the mongo shell to update the two documents with the field bal canverted from string data type to NumberDecimal:

db.collection.find( { bal: { $type: "string" } }
).forEach( doc => { doc.bal = NumberDecimal(doc.bal); db.collection.updateOne( { _id: doc._id }, { $set: { bal: doc.bal } } ); } )

After the update, the documents:

{ "_id" : 1, "bal" : NumberDecimal("123.45") }
{ "_id" : 2, "bal" : NumberDecimal("67890") }
{ "_id" : 3, "bal" : 999 }