在使用 Codeigniter MongoDB 庫的過程當(dāng)中,遇到了在查詢時(shí)需要計(jì)算某個(gè)字段和的需求
想到在 Mysql 中有 Sum 方法可用,不知道 CI MongoDB 是否也有呢?
結(jié)果卻發(fā)現(xiàn)在 CI MongoDB 庫中并未提供此類方法
無奈之下,只好翻閱文檔,寫下此 CI MongoDB 擴(kuò)展,以便已之需!
/* 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);
}
}