Convert a string to a number in MongoDB projection

后端 未结 3 665
谎友^
谎友^ 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:33

    Now there is $toInt conversion operators in aggregation, you can check: https://jira.mongodb.org/browse/SERVER-11400

    0 讨论(0)
  • 2020-12-10 06:45

    The core operation is to convert value from string to number which is unable to handled in aggregate pipeline operation currently.
    mapReduce is an alternative as below.

    db.c.mapReduce(function() {
        emit( this.groupId, {score: Number(this.value), count: 1} );
    }, function(key, values) {
        var score = 0, count = 0;
        for (var i = 0; i < values.length; i++) {
            score += values[i].score;
            count += values[i].count;
        }
        return {score: score, count: count};
    }, {finalize: function(key, value) {
        return {score: value.score / value.count};
    }, out: {inline: 1}});
    
    0 讨论(0)
  • 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"}
       }
    }]);
    
    0 讨论(0)
提交回复
热议问题