Convert a string to a number in MongoDB projection

后端 未结 3 667
谎友^
谎友^ 2020-12-10 06:05

I have a collection of documents that have a value that is known to be a number, but is stored as a string. It is out of my control to change the type of the field, but I w

3条回答
  •  抹茶落季
    2020-12-10 06:50

    One of the way which I can think of is to use a mongo shell javascript to modify the document by adding new number field, valuesasnumber (number conversion of existing string 'value' field) in the existing document or in the new doc. Then using this numeric field for further calculations.

    db.numbertest.find().forEach(function(doc) {
        doc.valueasnumber = new NumberInt(doc.value);
        db.numbertest.save(doc);
    });
    

    Using the valueasnumber field for numeric calculation

    db.numbertest.aggregate([{$group : 
       {_id : null, 
        "score" : {$avg : "$valueasnumber"}
       }
    }]);
    

提交回复
热议问题