Taking sum of “column” in MongoDB

后端 未结 7 525

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'];
    
    0 讨论(0)
  • 2020-12-10 19:35

    Another solution is to create a script in the database, that will sum the require data and return your result something like:

    The Script

    function sum() {
       var sum = 0;
       for (var query = db.collection.find({}, {type: 1, _id:0}); query.hasNext();) {
          sum += query.next();
       }
       return sum;
    }
    

    PHP

    In php after setting the connection with the db, it will be something like:

    $toexec = 'function(x, y) { return sum() }';
    $response = $database->execute($toexec, array());
    

    Look this tutorial to learn more about scripting in mongo with php.

    http://pointbeing.net/weblog/2010/08/getting-started-with-stored-procedures-in-mongodb.html

    0 讨论(0)
  • 2020-12-10 19:43

    This can be done with the following map reduce functions:

    var map = function () {
        emit("total", {sum:this.type}) 
        }
    
    var reduce = function (key, values) {
        var result = {sum:0};
        values.forEach(function (value) {result.sum += value.type;});
        return result;
        }
    
    db.table.mapReduce(map, reduce, {out : "type_totals"})
    

    or in php:

    $db->table->mapReduce( array( 
       'map' =>
       'function () {
          emit("total", {sum:this.type});
     }' 
    ,'reduce' =>
       'function (key, values) {
          var result = {sum:0};
          values.forEach(function (value) {result.sum += value.type;});
          return result;
         }'));
    
    0 讨论(0)
  • 2020-12-10 19:43
    Try:
    $m = new MongoClient();
    $con = $m->selectDB("dbName")->selectCollection("collectionName");
    $cond = array(
        array(
            '$group' => array(
                '_id' => null,
               'total' => array('$sum' => '$type'),
            ),
        )
    );
    
    $out = $con->aggregate($cond);
    print_r($out);
    

    More detail click here

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

    Utilizing MongoDB's new Aggregation Framework:

    $result = $db->command(array(
    
        'aggregate' => 'COLLECTION_NAME',
    
        'pipeline'  => array(
            // Match:
            // We can skip this in case that we don't need to filter 
            // documents in order to perform the aggregation
            array('$match' => array(
                // Criteria to match against
            )),
    
            // Group:
            array('$group'  => array(
                // Groupby fields:
                '_id'       => "$fieldname1, $fieldname2, $or_empty, $etc",
                // Count:
                'count'     => array('$sum' => 1),
                // Sum:
                'type_sum'  => array('$sum' => '$type'),
            ))
    
            // Other aggregations may go here as it's really a PIPE :p
    
        ),
    ));
    
    0 讨论(0)
  • 2020-12-10 19:45

    Other answers have already given lot many sources. Just giving answer for asked question:

    db.YOUR_COLLECTTION.aggregate([ { 
        $group: { 
            _id: null, 
            total: { 
                $sum: "$type" 
            } 
        } 
    } ] )
    
    0 讨论(0)
提交回复
热议问题