Taking sum of “column” in MongoDB

后端 未结 7 524

In MySQL, I would simply go \"SELECT sum(pts) FROM table\" to get the sum of the pts column on the table. However, I am converting this application to MongoDB and cannot fin

7条回答
  •  眼角桃花
    2020-12-10 19:33

    $mongo = new Mongo();
    
    $map = new MongoCode("function() { emit('total', this.type); }");
    $reduce = new MongoCode("function(k, vals) {
        var sum = 0;
        for(i in vals) {
            sum += vals[i];
        }
    
        return sum;
    }");
    
    $sumtotal = $mongo->db->command(array(
        'mapreduce' => 'tableName',
        'map' => $map,
        'reduce' => $reduce,
        // 'query' => array('col' => 'value'),
        'out' => array('merge' => 'tableName_sum')
    ));
    
    $result = $mongo->db->selectCollection($sumtotal['result'])->findOne();
    $sum = $result['value'];
    

提交回复
热议问题