mongodb分組統計

weixin_34293059發表於2018-04-14

從使用過程感受來看,MongoDB的語法還是很強大的,但是確實也很有限制
限制一:
我們經常要group by 多個欄位。但是MongoDB沒有找到方案
mysql的巢狀查詢沒有找到MongoDB的替代方案
比如:select count(*) from (select date from table group by date)

$data = [
            ['$match' =>
                [
                    'channel_attribute' =>
                    [
                        '$in' => explode(",", $where["channel_attribute"]),
                    ]
                ],
            ],
            ['$group' =>
                [
                    '_id' => ['$create_date'],
                    'channel_id' =>
                        [
                            '$first' => '$channel_id'
                        ],
                    'create_date' =>
                        [
                            '$first' => '$create_date'
                        ],
                    'sum_wx_user_num' =>
                        [
                            '$sum' => '$wx_user_num'
                        ],
                    'phone_user_num' =>
                        [
                            '$sum' => '$phone_user_num'
                        ],
                    'trade_sum_fee' =>
                        [
                            '$sum' => '$trade_sum_fee'
                        ],
                    'anticipated_income' =>
                        [
                            '$sum' => '$anticipated_income'
                        ]
                ]
            ],
//            ['$limit' => $page_num],
//            ['$skip' => 0],
        ];

        // 過濾時間
        if(isset($where["from_date"]) && $where["from_date"] != ''){
            $date['$gte'] = $where["from_date"];
        }
        if(isset($where["to_date"]) && $where["to_date"] != ''){
            $date['$lte'] = $where["to_date"];
        }
        if(isset($date)) $data[0]['$match']['create_date'] = $date;

        // 過濾計數級別
        if(isset($where["channel_depth"]) && $where["channel_depth"] != ''){
            $depth['$lte'] = $where["channel_depth"];
            $data[0]['$match']['channel_depth'] = $depth;
        }

        $cursor = $this->mongo->aggregate($data);
        print_r(iterator_to_array($cursor));exit;

相關文章