Taking sum of “column” in MongoDB

后端 未结 7 523

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: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
    
        ),
    ));
    

提交回复
热议问题