当前位置:

Yii2中mongodb的聚合操作

温馨提示:本文共1642个字,读完预计5分钟。

最近项目使用到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);
 

转载:https://www.cnblogs.com/two-bees/p/10483435.html

本文链接:,转发请注明来源!
评论已关闭。