Codeigniter MongoDB 擴(kuò)展之使用Aggregate方法實(shí)現(xiàn)Mysql的Sum方法

在使用 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);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容