1.安裝jenssegers/mongodb
composer require jenssegers/mongodb
2.定義model
class XXMODEL extends Jenssegers\Mongodb\Eloquent\Model implements Transformable { use TransformableTrait; protected $connection = 'CONNECTTION_NAME'; protected $collection = 'COLLECTION_NAME'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = []; }
3.列表+篩選+分類
public function list($where){ if (!empty($where['limit'])) { $limit = $where['limit']; unset($where['limit']); } else { $limit = config('repository.pagination.limit'); } $data = XXMODEL::raw(function ($collection) use($limit,$where) { //條件 $aggregate = array(); //查詢數組 $selectArr = array(); if(!empty($where['select']['keyword'])){ $selectArr['keyword'] = ['$regex' => ''. $where['select']['keyword'] . '', '$options' => "i"]; } if(!empty($where['select']['city'])){ $selectArr['value.city'] = $where['select']['city']; } //聚合數組 $groupArr = $groups = array(); if(!empty($where['groups']['keyword'])){ $groupArr['keyword'] = '$keyword'; } if(!empty($where['groups']['city'])){ $groupArr['city'] = '$value.city'; } if(!empty($groupArr)){ $groups['_id'] = $groupArr; $groups['sum_clicks'] = ['$sum' => '$click_nums']; } $aggregate[]['$match'] = $selectArr; if(!empty($groups)){ $aggregate[]['$group'] = $groups; } $count = sizeof($collection->aggregate($aggregate)->toArray()); //先排序在分頁 if(!empty($where['groups']['date'])){ $sort = ['_id.date' => -1]; }else{ $sort = ['date' => -1]; } $aggregate[]['$sort'] = empty($where['sort']) ? $sort : [$where['sort']['name'] => $where['sort']['order']]; $aggregate[]['$skip'] = ((empty($where['page']) ? 1 : $where['page'])-1) * $limit; $aggregate[]['$limit'] = $limit; //生成paginate分頁的格式方便前端 return new LengthAwarePaginator($collection->aggregate($aggregate)->toArray(), $count, $limit,!empty($where['page'])?$where['page']:1, [ 'path' => Paginator::resolveCurrentPath(), 'pageName' => 'page', ]); }); return $data; }