1. 程式人生 > >Yii2的mongodb的聚合操作

Yii2的mongodb的聚合操作

yii2 start rep 創建時間 mongod eve type name end

最近項目使用到mongodb的聚合操作,但是yii文檔中對這方面資料較少,記錄下

        $where[‘created_time‘] = [‘$gt‘ => "$start_date_str", ‘$lte‘ => "$end_date_str"];
        $where[‘token‘] = [‘$ne‘ => null];
        $where[‘app‘] = $app;
        $where[‘source_type‘] = $source_type;
        $loanmarket_info = Loanmarket::find()->asArray()->orderBy(‘created_time DESC‘)->all();
        if (!empty($keyword)) {
            $loanmarket_info = Loanmarket::find()->where([‘or‘,[‘like‘,‘name‘,$keyword],[‘like‘,‘number‘,$keyword]])->asArray()->orderBy(‘created_time DESC‘)->all();
            $keyword_arr = array_reduce($loanmarket_info, function ($result, $value) {
                return array_merge($result, array_values($value));
            }, array());
            if (!empty($keyword_arr)) {
                $where[‘lm_number‘] = [‘$in‘ => $keyword_arr];
            }
        }

        $aggregate = [
            [‘$match‘ => $where]    // 按照創建時間篩選,同時 token 不為空
            , [‘$group‘ => ["_id" => ["lm_number" => ‘$lm_number‘, "source_type" => ‘$source_type‘, "app" => ‘$app‘, "token" => ‘$token‘]]]  // token 去重
            , [‘$group‘ => ["_id" => ["lm_number" => ‘$_id.lm_number‘, "source_type" => ‘$_id.source_type‘, "app" => ‘$_id.app‘], "COUNT(token)" => [‘$sum‘ => 1]]]  // 統計UV
            , [‘$project‘ => ["_id" => 0, "lm_number" => ‘$_id.lm_number‘, "source_type" => ‘$_id.source_type‘, "app" => ‘$_id.app‘, "uv" => ‘$COUNT(token)‘]] // 顯示相應的字段
        ];
//        $query = new \yii\mongodb\Query;
//        $data_arr = $query->from([‘數據庫名‘,‘數據表名‘])->offset(3)->limit(5)->aggregate($aggregate);
        $data_arr = MongoBizEventReport::getCollection()->aggregate($aggregate);

  

Yii2的mongodb的聚合操作