MongoDB将字符串类型转换为浮点类型

MongoDB将字符串类型转换为浮点类型,mongodb,mongo-shell,Mongodb,Mongo Shell,按照这里的建议,我尝试更新我的集合以更改字段的类型及其值 这是更新查询 db.MyCollection.find({"ProjectID" : 44, "Cost": {$exists: true}}).forEach(function(doc){ if(doc.Cost.length > 0){ var newCost = doc.Cost.replace(/,/g, '').replace(/\$/g, ''); doc.Cost = pars

按照这里的建议,我尝试更新我的集合以更改字段的类型及其值

这是更新查询

db.MyCollection.find({"ProjectID" : 44, "Cost": {$exists: true}}).forEach(function(doc){
    if(doc.Cost.length > 0){
        var newCost = doc.Cost.replace(/,/g, '').replace(/\$/g, '');
        doc.Cost =  parseFloat(newCost).toFixed(2);  
        db.MyCollection.save(doc);
        } // End of If Condition
    }) // End of foreach
完成上述查询后,当我运行以下命令时

db.MyCollection.find({"ProjectID" : 44},{Cost:1})
我仍然有
成本
字段作为字符串

{
    "_id" : ObjectId("576919b66bab3bfcb9ff0915"),
    "Cost" : "11531.23"
}

/* 7 */
{
    "_id" : ObjectId("576919b66bab3bfcb9ff0916"),
    "Cost" : "13900.64"
}

/* 8 */
{
    "_id" : ObjectId("576919b66bab3bfcb9ff0917"),
    "Cost" : "15000.86"
}
我做错了什么

这是示例文档

/* 2 */
{
    "_id" : ObjectId("576919b66bab3bfcb9ff0911"),
    "Cost" : "$7,100.00"
}

/* 3 */
{
    "_id" : ObjectId("576919b66bab3bfcb9ff0912"),
    "Cost" : "$14,500.00"
}

/* 4 */
{
    "_id" : ObjectId("576919b66bab3bfcb9ff0913"),
    "Cost" : "$12,619.00"
}

/* 5 */
{
    "_id" : ObjectId("576919b66bab3bfcb9ff0914"),
    "Cost" : "$9,250.00"
}

问题是
toFixed
返回的是
字符串
,而不是
数字
。然后,您只需使用新的、不同的
字符串更新文档

来自Mongo Shell的示例:

> number = 2.3431
2.3431
> number.toFixed(2)
2.34
> typeof number.toFixed(2)
string
如果你想要一个2位小数,你必须用类似以下的东西再次解析它:

db.MyCollection.find({"ProjectID" : 44, "Cost": {$exists: true}}).forEach(function(doc){
  if(doc.Cost.length > 0){
    var newCost = doc.Cost.replace(/,/g, '').replace(/\$/g, '');
    var costString = parseFloat(newCost).toFixed(2);
    doc.Cost = parseFloat(costString);
    db.MyCollection.save(doc);
  } // End of If Condition
}) // End of foreach

按照此模式将字符串类型的货币字段转换为浮动。您需要查询集合中具有成本字段类型字符串的所有文档。为此,您需要利用进行批量更新。它们提供了更好的性能,因为您将以成批的方式(比如1000次)将操作发送到服务器,这为您提供了更好的性能,因为您不是每1000次请求都向服务器发送一次请求,而是每1000次请求只发送一次

下面演示了这种方法,第一个示例使用MongoDB版本
=2.6和<3.2
中提供的批量API。它更新了所有内容 通过将所有
成本
字段更改为浮动值字段,可以删除集合中的文档:

var bulk = db.MyCollection.initializeUnorderedBulkOp(),
    counter = 0;

db.MyCollection.find({ 
    "Cost": { "$exists": true, "$type": 2 } 
}).forEach(function (doc) {
    var newCost = Number(doc.Cost.replace(/[^0-9\.]+/g,"")); 
    bulk.find({ "_id": doc._id }).updateOne({ 
        "$set": { "Cost": newCost }
    });

    counter++;
    if (counter % 1000 == 0) {
        bulk.execute(); // Execute per 1000 operations 
        // re-initialize every 1000 update statements
        bulk = db.MyCollection.initializeUnorderedBulkOp(); 
    }
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }

下一个示例适用于新的MongoDB版本3.2,该版本自发布以来一直在使用提供一组更新的API

它使用与上面相同的游标,但使用相同的
forEach()
cursor方法创建具有批量操作的数组,以将每个批量写入文档推送到数组中。因为write命令最多只能接受1000个操作,所以您需要将操作分组为最多1000个操作,并在循环达到1000次迭代时重新初始化阵列:

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

cursor.forEach(function(doc){ 
    var newCost = Number(doc.Cost.replace(/[^0-9\.]+/g,""));
    bulkUpdateOps.push({ 
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": { "$set": { "Cost": newCost } }
         }
    });

    if (bulkUpdateOps.length == 1000) {
        db.MyCollection.bulkWrite(bulkUpdateOps);
        bulkUpdateOps = [];
    }
});         

if (bulkUpdateOps.length > 0) { db.MyCollection.bulkWrite(bulkUpdateOps); }

@chridam请使用这个{“_id”:ObjectId(“576919b66bab3bfcb9ff0915”),“Cost”:“$11531.23”}@user3100115,用示例文档更新。谢谢你的详细回答。数字(…)会保存十进制值吗?是的,是一个包装器对象,允许你处理数值。如果我可以问一下“$type”的意义是什么:2这真是太棒了。。感谢这是最好的答案-对任何大数据集(>20000个文档)执行此查询可能会失败。使用BulkOps是正确的方法。