PHP7连接Mongo

PHP7连接Mongo

#PHP7连接mongo
protected $conn = null;
protected $database = null;//MongoDB数据库名

public function _initialize()
{
    $this->conn = self::getMongoDB();
    $this->database = Config::get('mongo.database');
}

//连接mongoDB
public static function getMongoDB(){
    $arrConfig = Config::get('mongo');
    $uri = 'mongodb://' . $arrConfig['hostname'] . ':' . $arrConfig['hostport'];
    $mongo = new Manager($uri);
    if (!$mongo) parent::returnCode(2000,'mongoDB连接失败!');
    return $mongo;
}

/**
  * mongodb查询
  * @param array $filter    查询条件
  * @param int $offset      分页
  * @param int $limit       分页
  * @param null $db         collection
  * @param array $sort      排序条件
  * @return mixed
  */
public function query($filter = [],$offset = 1,$limit = 10,$db = null,$sort = ['x'=>-1]){
    //where条件
    $options = [
        'projection' => [
            '_id' => 0,
        ],//不显示或显示哪些字段
        'sort' => $sort,//排序
        'skip' => (int)$offset,//分页页数
        'limit' => (int)$limit,//条数
    ];
    $query = new Query($filter,$options);
    $cursor = $this->conn->executeQuery($this->database . '.' . $db,$query);
    $cursor = $cursor->toArray();
    return $cursor;
}

//获取查询条数
public function count($filter = [],$db = null){
    $comm['count'] = $db;
    if ($filter) $comm['query'] = $filter;
    $command = new Command($comm);
    return $this->conn->executeCommand($this->database,$command)->toArray()[0]->n;//db
}

#分组统计
public function group($filter = []){
    $cmd = new Command($filter);
    return $this->conn->executeCommand($this->database, $cmd)->toArray();
}

示例

#分组查询
$postfix = Directconst::getTablePostfix($id);
$str = 'trun_task_record_' . $postfix;//任务奖励明细
if (!$start){
    $start = mktime(0,0,0,date('m'),date('d'),date('Y'));
    $end = mktime(23,59,59,date('m'),date('d'),date('Y'));
}
$filter = [
    'aggregate' => $str,
    'pipeline' => [
        [
            '$match' => [//搜索条件
                'createTime' => ['$gte' => (int)$start,'$lt'=>(int)$end],
                'userId' => (int)$id
            ]
        ],
        [
            '$group' => [
                '_id' => ['taskId'=>'$taskId','date'=>'$date'],//多字段分组
                'count' => [//count统计
                    '$sum' => 1
                ]
            ]
        ]
    ],
    'cursor' => [
        'batchSize' => 0
    ]
];
$data = $mongo->group($filter);

//普通查询
$str = 'turn_user_sign';//mongoDB  collection
$filter['userId'] = (int)$id;//搜索条件
if ($start){
    $filter['createTime'] = [
        '$gte' => $start,
        '$lte' => $end
    ];
}
$sort = ['sort' => 1];//排序
if ($order == 'desc') $sort = ['sort' => -1];
$rows = $mongo->query($filter,$offset,$limit,$str,$sort);//数据
$total = $mongo->count($filter,$str);//总条数
原文地址:https://www.cnblogs.com/ljkltt/p/14809232.html