PHP封装一个MongoDB单例类

代码如下:

<?php

namespace app\index\cache;

/**
 * MongoDB单例类
 *
 */
class Mongo {
    private static $ins     = [];
    private static $def     = "test";
    private $_conn          = null;
    private $_db            = null;
    private static $_config = [
        "test" => ["url" => "mongodb://127.0.0.1:27017","dbname" => "mydb1"], //默认连接该库
    ];

    /**
     * 创建实例
     * @param  string $confkey
     * @return \Mongo
     */
    public static function getInstance($confkey = NULL) {
        if (!$confkey) {
            $confkey = self::$def;
        }
        if (!isset(self::$ins[$confkey]) && ($conf = self::$_config[$confkey])) {
            $m = new Mongo($conf);
            self::$ins[$confkey] = $m;
        }
        return self::$ins[$confkey];
    }

    /**
     * 构造方法
     */
    private function __construct(array $conf) {
        $this->_conn = new \MongoDB\Driver\Manager($conf["url"]."/{$conf["dbname"]}");
        $this->_db   = $conf["dbname"];
    }

    /**
     * 插入数据
     * @param  string $collname
     * @param  array  $documents    [["name"=>"values", ...], ...]
     * @param  array  $writeOps     ["ordered"=>boolean,"writeConcern"=>array]
     * @return \MongoDB\Driver\Cursor
     */
    function insert($collname, array $documents, array $writeOps = []) {
        $cmd = [
            "insert"    => $collname,
            "documents" => $documents,
        ];
        $cmd += $writeOps;
        return $this->command($cmd);
    }

    /**
     * 删除数据
     * @param  string $collname
     * @param  array  $deletes      [["q"=>query,"limit"=>int], ...]
     * @param  array  $writeOps     ["ordered"=>boolean,"writeConcern"=>array]
     * @return \MongoDB\Driver\Cursor
     */
    function del($collname, array $deletes, array $writeOps = []) {
        foreach($deletes as &$_){
            if(isset($_["q"]) && !$_["q"]){
                $_["q"] = (Object)[];
            }
            if(isset($_["limit"]) && !$_["limit"]){
                $_["limit"] = 0;
            }
        }
        $cmd = [
            "delete"    => $collname,
            "deletes"   => $deletes,
        ];
        $cmd += $writeOps;
        return $this->command($cmd);
    }

    /**
     * 更新数据
     * @param  string $collname
     * @param  array  $updates      [["q"=>query,"u"=>update,"upsert"=>boolean,"multi"=>boolean], ...]
     * @param  array  $writeOps     ["ordered"=>boolean,"writeConcern"=>array]
     * @return \MongoDB\Driver\Cursor
     */
    function update($collname, array $updates, array $writeOps = []) {
        $cmd = [
            "update"    => $collname,
            "updates"   => $updates,
        ];
        $cmd += $writeOps;
        return $this->command($cmd);
    }

    /**
     * 查询
     * @param  string $collname
     * @param  array  $filter     [query]     参数详情请参见文档。
     * @return \MongoDB\Driver\Cursor
     */
    function query($collname, array $filter, array $writeOps = []) {
        $cmd = [
            "find"      => $collname,
            "filter"    => $filter
        ];
        $cmd += $writeOps;
        return $this->command($cmd);
    }

    /**
     * 执行MongoDB命令
     * @param array $param
     * @return \MongoDB\Driver\Cursor
     */
    function command(array $param) {
        $cmd = new \MongoDB\Driver\Command($param);
		//var_dump($cmd);
        return $this->_conn->executeCommand($this->_db, $cmd);
    }

    /**
     * 获取当前mongoDB Manager
     * @return MongoDB\Driver\Manager
     */
    function getMongoManager() {
        return $this->_conn;
    }
}


//调用示例
//$collname = "test"; //集合名
//
////插入
//$rows = [
//    ["name" => "ns w1","type"=>"ns","size"=>["height"=>150,"width"=>30],"price"=>3000],
//    ["name" => "ns hd","type"=>"ns","size"=>["height"=>154,"width"=>30],"price"=>3500],
//    ["name" => "ns w3","type"=>"ns","size"=>["height"=>160,"width"=>30],"price"=>3800],
//    ["name" => "bt s1","type"=>"bt","size"=>["height"=>158,"width"=>32],"price"=>3500],
//    ["name" => "bt w1","type"=>"bt","size"=>["height"=>157,"width"=>30],"price"=>3600],
//    ["name" => "an w1","type"=>"bt","size"=>["height"=>157,"width"=>30],"price"=>3700],
//    ["name" => "wn w6","type"=>"wn","size"=>["height"=>157,"width"=>30],"price"=>3500],
//];
//$rs = Mongo::getInstance()->insert($collname, $rows);
//print_r($rs->toArray());die;;
//
//
////查询
//$aa = [
//    "find"=> "test",
//    "filter"    => [
//        "name" =>"ns w3"
//    ]
//];
//$data = Mongo::getInstance()->command($aa);
//var_dump($data->toArray());die;
//
//
////删除
//$delets = [
//    ["q" => [],"limit" => 0]
//];
//$rs = Mongo::getInstance()->del($collname, $delets);
//print_r($rs->toArray());
//
//
////创建索引
//$cmd = [
//    "createIndexes" => $collname,
//    "indexes"       => [
//        ["name" => "proname_idx", "key" => ["name"=>1],"unique" => true],
//    ],
//];
//$rs = Mongo::getInstance()->command($cmd);
//print_r($rs->toArray());
//
//
////查询索引
//$cmd = [
//    "listIndexes" => $collname,
//];
//$rs = Mongo::getInstance()->command($cmd);
//print_r($rs->toArray());
//
//
////查询数据
//$filter = [
//    "name" => ['$regex' => '\sw\d'], // mongo 正则匹配
//    '$or'  => [["type"  => "bt"], ["size.height" => ['$gte' => 160]]]
//];
//$queryWriteOps = [
//    "projection" => ["_id"   => 0],
//    "sort"       => ["price" => -1],
//    "limit"      => 20
//];
//$rs = Mongo::getInstance()->query($collname, $filter, $queryWriteOps);
//print_r($rs->toArray());
//
//
////更新数据
//$updates = [
//    [
//        "q"     => ["name" => "ns w3"],
//        "u"     => ['$set' => ["size.height" => 140],'$inc' => ["size.width" => 14]],
//        "multi" => true,
//    ]
//];
//$rs = Mongo::getInstance()->update($collname, $updates);
//print_r($rs->toArray());
发布了120 篇原创文章 · 获赞 433 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/msllws/article/details/104242660