在使用 Codeigniter MongoDB 库的过程当中,遇到了在查询时需要计算某个字段和的需求
想到在 Mysql 中有 Sum 方法可用,不知道 CI MongoDB 是否也有呢?
结果却发现在 CI MongoDB 库中并未提供此类方法
无奈之下,只好翻阅文档,写下此 CI MongoDB 扩展,以便已之需!
/* Controller.php */
$option = array (
array (
'$match' => array (
'match_1' => 'value_1',
'match_2' => 'value_2'
)
),
array (
'$group' => array (
'_id' => null,
'sum_1' => ['$sum' => '$amount_1'],
'sum_2' => ['$sum' => '$amount_2'],
'sum_3' => ['$sum' => '$amount_3']
)
)
);
$result = $this -> mongo_db -> aggregate('collection', $option);
/* Mongo_db.php */
public function aggregate ($collection, $option = array())
{
try {
return $this -> db -> {$collection} -> aggregate($option);
}
catch (Exception $e) {
show_error("Unable to aggregate Mongo Databases: {$e->getMessage()}", 500);
}
}