Mongo convert all numeric fields that are stored as string

后端 未结 2 742
陌清茗
陌清茗 2020-12-18 06:29

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 calcul

2条回答
  •  佛祖请我去吃肉
    2020-12-18 07:05

    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) } }
            )
        }
    })
    

    It loops through each document, uses isNaN as you suggested, then $sets the value to the parseFloat value for the current document.

提交回复
热议问题