将MongoDB字段类型从字符串更新为带小数的数字 [英] Update MongoDB field type from string to number with decimals

查看:2559
本文介绍了将MongoDB字段类型从字符串更新为带小数的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的数据。所有字段都存储为字符串。我需要将 amount 字段设置为双精度格式。

I have data in the following format. All the fields are stored as strings. I need to get the amount field to Double format.

{
    "_id" : "soZkg8bvRfM6DHxgW", // string
    "itemId" : "1",              // string
    "amount" : "3113.40",        // string
    "type" : "Travel"            // string
}



我试过这个操作,更新, amount 的值为3113.00,而不是3113.40

I tried this operation, but after the update, the value of amount is 3113.00, not 3113.40

db.collection.find().forEach( function (x) {
  x.amount = parseInt(x.amount).toFixed(2); 
  db.collection.save(x);
});

那么如何将字符串转换为支持数字的数字格式,十进制值?或者我应该使用其他格式吗?

So how can I convert from string to a number format that supports digits, and does not reset my current decimal values? Or should I use another format?

我需要能够与金额数据进行汇总。

I need to be able to do aggregations with the amount data.

推荐答案

会说批量操作,因为它们允许执行批量更新操作,这些操作只是服务器上的抽象操作,可以轻松构建批量操作,从而简化您的更新。

Would say go for the bulk operations as they allow for the execution of bulk update operations which are simply abstractions on top of the server to make it easy to build bulk operations, thus streamlining your updates.

您可以通过 批量API 批量发送写入操作,甚至更好,它给你真正的反馈,成功和失败。

You get performance gains over large collections as the bulk API sends write operations in bulk, and even better, it gives you real feedback about what succeeded and what failed.

在批量更新中,使用 parseFloat() 来解析字符串值并返回浮点数。您还需要首先过滤集合以优化更新,并将更新操作批量发送到服务器说500,这将提供更好的性能,因为您不会发送每个请求到服务器,每500个请求只有一次:

In the bulk update, use parseFloat() to parse the string value and return a floating point number. You will also need to filter the collection first to optimise the updates and send the update operations to the server in batches of say 500 which gives you a better performance as you are not sending every request to the server, just once in every 500 requests:

var cursor = db.collection.find({
        "amount": { 
            "$exists": true, 
            "$type": 2 
        }
    }),
    bulkUpdateOps = [];

cursor.forEach(function(doc){ 
    bulkUpdateOps.push({ 
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": { 
                "$set": { "amount": parseFloat(doc.amount) }
            }
        }
    });

    if (bulkUpdateOps.length === 500) {
        db.collection.bulkWrite(bulkUpdateOps);
        bulkUpdateOps = [];
    }
});         

if (bulkUpdateOps.length > 0) 
    db.collection.bulkWrite(bulkUpdateOps)

这篇关于将MongoDB字段类型从字符串更新为带小数的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆