MongoCli.php 6.5 KB
<?php
namespace Jiaoyin;

class MongoCli
{
    private $pool;
    private $database;
    public function __construct($host,$port,$username,$password,$database, $num = 20)
    {
        $this->database = $database;
        $userInfo = $username?"{$username}:{$password}@":"";
        $dsn = "mongodb://{$userInfo}{$host}:{$port}/{$database}";
        $this->pool = new MongoPool($dsn,$num);
    }

    /*
     * 创建集合
     */
    public function createCollection($table,$createIndex=[]){
        try {
            $mongodb = $this->pool->get();
            $database = $mongodb->selectDatabase($this->database);
            $collections = $database->listCollections(['filter' => ['name' => $table]]);
            $collectionExists = iterator_count($collections) > 0;
            if (empty($collectionExists)) {
                // 集合不存在,创建集合并添加索引
                $database->createCollection($table);
                $collection = $database->selectCollection($table);
                $collection->createIndex($createIndex);
            }
            $this->pool->push($mongodb);
        } catch (\Exception $e) {
            output($e->getMessage());
        }
    }
    /*
     * 检查集合是否存在
     * */
    public function checkCollection($table): bool
    {
        try {
            $mongodb = $this->pool->get();
            $database = $mongodb->selectDatabase($this->database);
            $collections = $database->listCollections(['filter' => ['name' => $table]]);
            $collectionExists = iterator_count($collections) > 0;
            $this->pool->push($mongodb);
            if (empty($collectionExists)) {
                // 集合不存在
                return false;
            }
            return true;
        } catch (\Exception $e) {
            output($e->getMessage());
            return false;
        }
    }

    /*
     * 写入数据
     * $collection->insertOne(['name' => 'John Doe']);
     * */
    public function insertOne($table,$data = [])
    {
        try {
            $mongodb = $this->pool->get();
            $database = $mongodb->selectDatabase($this->database);
            $collection = $database->selectCollection($table);
            $result = $collection->insertOne($data);
            $this->pool->push($mongodb);
            return $result;
        } catch (\Exception $e) {
            output($e->getMessage());
            return false;
        }
    }

    /*
     * 批量写入数据
     * $collection->insertMany([['name' => 'John Doe'],['name' => 'John Doe']]);
     * */
    public function insertAll($table,$data = [])
    {
        try {
            $mongodb = $this->pool->get();
            $database = $mongodb->selectDatabase($this->database);
            $collection = $database->selectCollection($table);
            $result = $collection->insertMany($data);
            $this->pool->push($mongodb);
            return $result;
        } catch (\Exception $e) {
            output($e->getMessage());
            return [];
        }
    }

    /*
     * 查询单条数据
     * $collection->findOne(['name' => 'John Doe']);
     * */
    public function findOne($table,$where = [])
    {
        try {
            $mongodb = $this->pool->get();
            $database = $mongodb->selectDatabase($this->database);
            $collection = $database->selectCollection($table);
            $result = $collection->findOne($where);
            $this->pool->push($mongodb);
            return $result;
        } catch (\Exception $e) {
            output($e->getMessage());
            return [];
        }
    }

    /*
     * 查询所有数据
     * $collection->findOne(['name' => 'John Doe']);
     * ['t' => ['$gt' => 1]]; // 查询大于1的数据
     * ['t' => ['$lt' => 1]]; // 查询小于1的数据
     * ['t' => ['$gte' => 1]]; // 查询大于等于1的数据
     * ['t' => ['$lte' => 1]]; // 查询小于等于1的数据
     * $options = [
     *   'sort' => ['field_name' => 1], // 1 表示升序,-1 表示降序,
     *   'limit' => 100,
     *  ];
     * */
    public function findAll($table,$where = [], $options=[])
    {
        try {
            $mongodb = $this->pool->get();
            $database = $mongodb->selectDatabase($this->database);
            $collection = $database->selectCollection($table);
            $result = $collection->find($where,$options);
            $this->pool->push($mongodb);
            // 遍历结果集
            $data = [];
            if ($result){
               $arr = $result->toArray();
                foreach ($arr as $item) {
                    $data[] = $item->getArrayCopy();
               }
                return $data;
            }
            return [];
        } catch (\Exception $e) {
            output($e->getMessage());
            return [];
        }
    }

    /*
     * 更新数据
     * $collection->updateOne(['name' => 'John Doe'], ['$set' => ['age' => 31]]);
     * */
    public function updateOne($table,$where = [],$upData = [])
    {
        try {
            $mongodb = $this->pool->get();
            $database = $mongodb->selectDatabase($this->database);
            $collection = $database->selectCollection($table);
            $result = $collection->updateOne($where,$upData);
            $this->pool->push($mongodb);
            return $result;
        } catch (\Exception $e) {
            output($e->getMessage());
            return [];
        }
    }

    /*
     * 删除数据
     * $collection->deleteOne(['name' => 'John Doe']);
     * */
    public function deleteOne($table,$where = [])
    {
        try {
            $mongodb = $this->pool->get();
            $database = $mongodb->selectDatabase($this->database);
            $collection = $database->selectCollection($table);
            $result = $collection->deleteOne($where);
            $this->pool->push($mongodb);
            return $result;
        } catch (\Exception $e) {
            output($e->getMessage());
            return [];
        }
    }

    /*
     * 批量删除数据
     * $collection->deleteMany(['name' => 'John Doe']);
     * */
    public function deleteBatch($table,$where = [])
    {
        try {
            $mongodb = $this->pool->get();
            $database = $mongodb->selectDatabase($this->database);
            $collection = $database->selectCollection($table);
            $result = $collection->deleteMany($where);
            $this->pool->push($mongodb);
            return $result;
        } catch (\Exception $e) {
            output($e->getMessage());
            return [];
        }
    }

}