简体   繁体   English

Mongodb将字符串解析为十进制/浮点数

[英]Mongodb parse string to Decimal/float

i'm new to mongoDB. 我是mongoDB的新手。 I got my data as a string but i want to parse it to a decimal/ float . 我将数据作为字符串获取,但是我想将其解析为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. 这是我的代码,它将-替换为00,将*替换为*,并将其解析为浮点数。 It gives no errors, but the parseFloat(doc).toFixed(2) . 它没有错误,但是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. 提前致谢。

You did this wrong. 你做错了 Convert first and the Number() function of the shell has nothing to do with it. 首先进行转换,外壳程序的Number()函数与此无关。 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 . 第二个参数在那里的.update()用法将用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. 它使用$set运算符,以便在写入数据库时​​不会覆盖doc对象中未引用的任何现有值。

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 . 我有一个类似的问题,我们没有正确启用十进制序列化,因此我想更新数据库中已有的文档,以使用Decimal类型代替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. 这仅通过过滤字段类型来检索需要更新的文档,然后使用NumberDecimal将字符串转换为十进制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM