Mongo converts all numeric fields that are stored as strings

It seems like for a while I save my decimal numbers as strings. This is now a problem because I need to start using the aggregation structure to perform some calculations.

Is there a way to skip every document in my collection and check each value for isNaN, and if false, save it withparseFloat

+5
source share
2 answers

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 scans each document, uses isNaN, as suggested, and then the $setsvalue for the value parseFloatfor the current document.

+6
source

. , , .

, :

var cursor = db.results.find();
while (cursor.hasNext()) {
    var doc = cursor.next();
    for (key in doc) {
        if (key.match(/^metric_.*/i) && !isNaN(doc[key])) {
            doc[key] = parseFloat(doc[key]);
            db.results.update({ _id : doc._id }, doc );
        }
    }
}

:

  • . , , , .
  • ! javascript isNaN . parseFloat isNaN. , , .

, - .

+2

All Articles