Mongo转换所有存储为字符串的数字字段 [英] Mongo convert all numeric fields that are stored as string
本文介绍了Mongo转换所有存储为字符串的数字字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在好像已经有一段时间我将小数存储为字符串了.现在这是一个问题,因为我需要开始使用聚合框架来执行一些计算.
It looks like for a while now I've been storing my decimals as strings. This is now a problem because I need to start using the aggregation framework to perform some calculations.
有什么方法可以遍历集合中的每个文档并检查isNaN
的每个值,如果为false,则使用parseFloat
Is there any way to walk each document in my collection and check each value for isNaN
, and if false, store it with parseFloat
推荐答案
在mongo shell中应该可以执行以下操作:
Something like this should work from the mongo shell:
db.yourCollection.find({}).forEach(function(doc) {
if(isNaN(doc.xyz)) {
print('found string: ' + doc._id);
db.yourCollection.update(
{ _id: doc._id},
{ $set : { "xyz" : parseFloat(doc.xyz) } }
)
}
})
它将遍历每个文档,按照您的建议使用isNaN
,然后将$sets
的值更改为当前文档的parseFloat
的值.
It loops through each document, uses isNaN
as you suggested, then $sets
the value to the parseFloat
value for the current document.
这篇关于Mongo转换所有存储为字符串的数字字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文