php封装MongoDB类

21 篇文章 1 订阅
3 篇文章 0 订阅

github:https://github.com/why444216978/php-mongo-library

Service:

​<?php
    require_once('./models/articleModel.php');
 
    class MongoService
    {
        private $_manager;
        private $_host;
        private $_username;
        private $_password;
        private $_db;
 
        public function connect($config)
        {
            if (empty($config)) {
                echo  'config is null';
                die;
            }
            if ($config == 'why') {
                $this->_host = '127.0.0.1';
                $this->_username = 'why';
                $this->_password = 'why123';
                $this->_db = 'why_db';
                $mongo = "mongodb://why:why123@127.0.0.1/";
            } else {
                echo 'config is error';
                die;
            }
            return    $this->_manager = new \MongoDB\Driver\Manager($mongo);
        }
 
        public function getDB()
        {
            return $this->_db;
        }
 
        public function setDB($db)
        {
            $this->_db = $db;
            return $this->_db;
        }
 
        public function getBulk()
        {
            return new \MongoDB\Driver\BulkWrite;
        }
 
        public function getWriteConcern()
        {
            return new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
        }
 
        /**
         * 插入数据
         * @param $db 数据库名
         * @param $collection 集合名
         * @param $document 数据 array格式
         * @return
         */
        public function insert($collection, $document)
        {
            $bulk = $this->getBulk();
            if (count($document) == 1) {
                $document['_id'] = new \MongoDB\BSON\ObjectID;
                $bulk->insert($document);
            } else {
                foreach ($document as $val) {
                    $val['_id'] = new \MongoDB\BSON\ObjectID;
                    $bulk->insert($val);
                }
            }
            $res = $this->_manager->executeBulkWrite($this->_db . '.' . $collection, $bulk);
            if (empty($res->getWriteErrors())) {
                return true;
            } else {
                return false;
            }
        }
 
        /**
         * 删除数据
         * @param array $where
         * @param array $option
         * @param string $db
         * @param string $collection
         * @return mixed
         */
        public function delete($collection, $where = array(), $option = array())
        {
            $bulk = $this->getBulk();
            $bulk->delete($where, $option);
            return $this->_manager->executeBulkWrite($this->_db . $collection, $bulk);
        }
 
        /**
         * 更新数据
         * @param array $where 类似where条件
         * @param array $field  要更新的字段
         * @param bool $upsert 如果不存在是否插入,默认为false不插入
         * @param bool $multi 是否更新全量,默认为false
         * @param string $db   数据库
         * @param string $collection 集合
         * @return mixed
         */
        public function update($collection, $where = array(), $field = array(), $upsert = false, $multi = false)
        {
            if (empty($where)) {
                return 'filter is null';
            }
            $bulk = $this->getBulk();
            $write_concern = $this->getWriteConcern();
            if (isset($where['_id'])) {
                $where['_id'] = new \MongoDB\BSON\ObjectId($where['_id']);
            }
            $bulk->update($where, array('$set' => $field), array('multi' => $multi, 'upsert' => $upsert));
            $res = $this->_manager->executeBulkWrite($this->_db . '.' . $collection, $bulk, $write_concern);
            if (empty($res->getWriteErrors())) {
                return true;
            } else {
                return false;
            }
        }
 
        public function selectById($collection, $id, $options = array())
        {
            //$filter = ['_id' => new \MongoDB\BSON\ObjectID($id)];
            //return $this->query($collection, $filter, $options);
            $filter = ['_id' => new \MongoDB\BSON\ObjectID($id)];
            $res = $this->query($collection, $filter, $options);
            foreach ($res as $item) {
                $data = $this->objToArray($item);
            }
            return $data;
        }
 
        public function query($collection, $filter, $options)
        {
            $query = new \MongoDB\Driver\Query($filter, $options);
            $res = $this->_manager->executeQuery($this->_db . '.' . $collection, $query);
            $data = array();
            foreach ($res as $item) {
                $tmp = $this->objToArray($item);
                $tmp['id'] = $tmp['_id']['$oid'];
                unset($tmp['_id']);
                $data[] = $tmp;
            }
            return $data;
        }
 
        /**
         * 执行MongoDB命令
         * @param array $param
         * @return \MongoDB\Driver\Cursor
         */
        public function command($param)
        {
            $cmd = new \MongoDB\Driver\Command($param);
            return $this->_manager->executeCommand($this->_db, $cmd);
        }
 
        /**
         * 按条件计算个数
         *
         * @param string $collName 集合名
         * @param array $where 条件
         * @return int
         */
        function count($collName, array $where)
        {
            $result = 0;
            $cmd = [
                'count' => $collName,
                'query' => $where
            ];
            $arr = $this->command($cmd)->toArray();
            if (!empty($arr)) {
                $result = $arr[0]->n;
            }
            return $result;
        }
 
        public function objToArray($obj)
        {
            return json_decode(json_encode($data), true);
        }
 
        public function getCol($col)
        {
            if (in_array($col, ['article'])) {
                $this->connect('why');
            } else {
                return 'collection error';
            }
            $col = ucwords($col);
 
            return new $col($this);
        }
    }
 
    ?>

Table对应的Model

<?php

class Article
{
    private $table = 'article';
    private $_mongo;

    public function __construct($mongo)
    {
        $this->_mongo = $mongo;
    }
    public function getAll($filter, $options)
    {
        $data = $this->_mongo->query($this->table, $filter, $options);
        return $data;
    }

    public function update($where, $data)
    {
        return $this->_mongo->update($this->table, $where, $data);
    }

    public function getCount($filter)
    {
        return $this->_mongo->count($this->table, $filter);
    }
}

index.php

<?php
require_once("./mongoService.php");
$mongo = new mongoService();

$article  = $mongo->getCol('article');

//设置过滤条件和选项
$filter = array();
if (!empty($keywords)) {
    $res = $this->getMediaFilter($keywords);
    $filter['media'] = ['$in' => array_values($res)];
}
if (!empty($source)) {
    $filter['source'] = $source;
}

$limit = 30;
$page  = 1;

$filter['created_time'] = [
    '$gte' => 1593532800,
    '$lt' => 1596211200
];

$options['sort']       =  ['pub_time' => -1]; //1-升序,2-降序
$options['limit']      = $limit;
$options['skip'] = ($page - 1) * $limit;
$options['projection'] = ['content' => 0];
//查询所有数据并处理
$data = $article->getAll($filter, $options);

//返回count
$count = $article->getCount($filter);

php使用aggregate:https://success.blog.csdn.net/article/details/86494442

参考博客:https://www.php.net/manual/en/class.mongodb-driver-manager.php

参考文档:https://www.runoob.com/mongodb/php7-mongdb-tutorial.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AirGo.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值