php7 mongoDB 封裝 支持多庫鏈接配置 簡單易用

mongoDB封裝 支持多庫鏈接配置 簡單 易用

示例代碼中包含mongoDB的基本操作,增、刪、改、查、索引、正則等。

請注意:mongoDB 支持版本 3.2+

因爲操作方都是使用command來執行,使用規範請參見官方文檔。

具體命令及參數等相關定義請參見:

https://docs.mongodb.com/manual/reference/command/


m_mgdb.php

<?php


/**
 * mongoDB 簡單 封裝
 * 請注意:mongoDB 支持版本 3.2+
 * 具體參數及相關定義請參見: https://docs.mongodb.com/manual/reference/command/
 *
 * @author color_wind
 */
final class m_mgdb {


    //--------------  定義變量  --------------//
    private static $ins     = [];
    private static $def     = "default";
    private $_conn          = null;
    private $_db            = null;
    private static $_config = [
        "default" => ["url" => "mongodb://username:passwd@localhost:27017","dbname" => "mydb1"],
        "mdb1"    => ["url" => "mongodb://10.0.0.12:27017","dbname" => "mydb2"],
    ];


    /**
     * 創建實例
     * @param  string $confkey
     * @return \m_mgdb
     */
    static function i($confkey = NULL) {
        if (!$confkey) {
            $confkey = self::$def;
        }
        if (!isset(self::$ins[$confkey]) && ($conf = self::$_config[$confkey])) {
            $m = new m_mgdb($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);
        return $this->_conn->executeCommand($this->_db, $cmd);
    }


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


}

測試代碼:

mongo_test.php

<?php

require_once 'm_mgdb.php';

// 示例代碼
//$db = m_mgdb::i("mdb1"); // 使用配置self::$_config["mdb1"]
$db = m_mgdb::i();         // 使用配置self::$_config[self::$def]
$collname = "proinfo";


// echo "\n---------- 查詢支持命令 -----------\n";
// $cmd = [
//     "listCommands" => 1,
// ];
// $rs = $db->command($cmd);
// print_r($rs->toArray());


echo "\n---------- 刪除 proinfo 所有數據 -----------\n";
$delets = [
    ["q" => [],"limit" => 0]
];
$rs = $db->del($collname, $delets);
print_r($rs->toArray());


echo "\n---------- 創建索引 -----------\n";
$cmd = [
    "createIndexes" => $collname,
    "indexes"       => [
        ["name" => "proname_idx", "key" => ["name"=>1],"unique" => true],
    ],
];
$rs = $db->command($cmd);
print_r($rs->toArray());


echo "\n---------- 查詢索引 -----------\n";
$cmd = [
    "listIndexes" => $collname,
];
$rs = $db->command($cmd);
print_r($rs->toArray());


echo "\n------------ 插入數據 ---------\n";
$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 = $db->insert($collname, $rows);
print_r($rs->toArray());


echo "\n---------- 查詢數據 -----------\n";
$filter = [
    "name" => ['$regex' => '\sw\d'], // mongo 正則匹配
    '$or'  => [["type"  => "bt"], ["size.height" => ['$gte' => 160]]]
];
$queryWriteOps = [
    "projection" => ["_id"   => 0],
    "sort"       => ["price" => -1],
    "limit"      => 20
];
$rs = $db->query($collname, $filter, $queryWriteOps);
print_r($rs->toArray());


echo "\n---------- 更新數據 -----------\n";
$updates = [
    [
        "q"     => ["name" => "ns w3"],
        "u"     => ['$set' => ["size.height" => 140],'$inc' => ["size.width" => 14]],
        "multi" => true,
    ]
];
$rs = $db->update($collname, $updates);
print_r($rs->toArray());


echo "\n---------- 查詢數據 -----------\n";
$filter = [
    "name" => "ns w3",
];
$rs = $db->query($collname, $filter, $queryWriteOps);
print_r($rs->toArray());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章