henktenk
henktenk

Reputation: 280

Mongodb parse string to Decimal/float

i'm new to mongoDB. I got my data as a string but i want to parse it to a decimal/ float. I found made this code but it doesn't seem to work. This is my code, it replaces - for 00, * for "", and parses it a float. It gives no errors, but the parseFloat(doc).toFixed(2).

db.behuizingen.find().forEach(function(doc)
{
    var price = doc.Prijs.replace('€', ''); // it may be vary for your other document
    price = price.replace('-', '00');  
    price = price.replace('*', '');  
    doc.Prijs = Number(price);
    parseFloat(doc).toFixed(2)

    db.behuizingen.update({_id : doc._id} , doc;
})

Thanks in advance.

Upvotes: 2

Views: 5824

Answers (2)

adrian
adrian

Reputation: 2923

I had a similar issue where we had not had decimal serialisation enabled correctly and so I wanted to update documents that were already in our database to use the Decimal type instead of String. I used the following script:

db.MyCollection.find({ Price: { $type: "string" } }).forEach(function(doc) { 
    print('Updating price for ' + doc._id);
    db.MyCollection.update( 
       { _id: doc._id },
       { $set : { Price: NumberDecimal(doc.Price) } }
    )
})

This only retrieves the documents that need updating by filtering on the field type, and then uses NumberDecimal to convert the string into a decimal.

Upvotes: 0

Neil Lunn
Neil Lunn

Reputation: 151112

You did this wrong. Convert first and the Number() function of the shell has nothing to do with it. So replacing that line an continuing:

doc.Prijs = parseFloat(parseFloat(price).toFixed(2));
db.moederborden.update({_id : doc._id} , doc );

But also be beware. That usage of .update() where the second argument is there will "replace" the entire document with the contents of doc.

You may want to do this instead:

doc.Prijs = parseFloat(parseFloat(price).toFixed(2));
var update = { "$set": {} };

Object.keys(doc).each(function(key) {
    update["$set"][key] = doc[key];
});

db.moederborden.update({_id : doc._id} , update );

Which uses the $set operator, so that any existing values that were not referenced in your doc object are not overwritten when writing to the database.

Upvotes: 4

Related Questions