MongoDB for PHP扩展操作类

28 篇文章 1 订阅

  1. <?php  
  2.   
  3. /** 
  4.  *   
  5. * @link        https://github.com/thendfeel/TmongoDB 
  6. * @example       
  7. * @copyright     
  8. * @site        http://www.uacool.com 
  9. * @created     2013-12-13 
  10. * 
  11. * Manual 
  12. * http://us2.php.net/mongo 
  13. * 针对阿里云MongoDB数据库 
  14. * SQL to Mongo Mapping Chart 
  15. * http://us2.php.net/manual/en/mongo.sqltomongo.php 
  16. * 单例模式(只针对相同的config) 
  17. */  
  18. class TmongoDB  
  19. {  
  20.   
  21.     protected $_db = 'test';  
  22.   
  23.     protected $_collection = 'user';  
  24.   
  25.     protected $_validate = array();  
  26.   
  27.     protected static $_mongoObj = array();  
  28.       
  29.     private $_exeResult = null;  
  30.     protected $_sql = array();  
  31.       
  32.     protected $_mongo = null;   
  33.       
  34.     const CONNECT_DB = 'admin'// 连接数据库,默认为admin  
  35.       
  36.     /** 
  37.      * Config For MongDB 
  38.      * 
  39.      * @var array 
  40.      */  
  41.     protected $_config = array(  
  42.             'mongo_seed1' => 'localhost',  
  43.             'mongo_seed2' => '',  
  44.             'mongo_replname' => '',  
  45.             'mongo_user' => NULL,  
  46.             'mongo_pwd' => NULL  
  47.     );  
  48.   
  49.     public function __construct($config,$db$collection)  
  50.     {  
  51.         foreach ($this->_config as $k => $v) {  
  52.             if(isset($config[$k])){  
  53.                 $this->_config[$k] = $config[$k];  
  54.             } else {  
  55.                 E('mongoDB数据库连接,请传递'.$k);  
  56.             }  
  57.         }  
  58.   
  59.         $this->_db = $db;  
  60.         $this->_collection = $collection;  
  61.           
  62.         $this->init();  
  63.     }  
  64.       
  65.     public function getMongo()  
  66.     {  
  67.         return $this->_mongo;  
  68.     }  
  69.       
  70.     /** 
  71.      * Init The Class 
  72.      * 对于相同的配置只初始化一次 
  73.      * @param string $db 
  74.      * @param string $collection 
  75.      */  
  76.     public function init()  
  77.     {  
  78.         $config = $this->_config;  
  79.         ksort($config);  
  80.         $encryptStr = '';  
  81.            
  82.         foreach ($config as $k => $v) {  
  83.             $encryptStr .= ($k.$v);  
  84.         }  
  85.           
  86.         $key = md5($encryptStr);  
  87.           
  88.         if (!self::$_mongoObj[$key]) {  
  89.             /*$conStr = "mongodb://"; 
  90.              
  91.             if ($config['user'] && $config['password']) { 
  92.                 $conStr .= "{$config['user']}:{$config['password']}@"; 
  93.             } 
  94.              
  95.             $conStr .= "{$config['host']}:{$config['port']}"; 
  96.              
  97.             $_mongoDB = new \Mongo($conStr, array( 
  98.                     "connect" => false 
  99.             ));*/  
  100.             $demo_uri = 'mongodb://' . $config['mongo_user'] . ':' . $config['mongo_pwd'] . '@' .  
  101.                     $config['mongo_seed1'] . ',' . $config['mongo_seed2'] . '/' . self::CONNECT_DB . '?replicaSet=' . $config['mongo_replname'];  
  102.            
  103.             $manager = new \MongoDB\Driver\Manager($demo_uri);  
  104.               
  105.             self::$_mongoObj[$key] = $this->_mongo = $manager;  
  106.                
  107.             /*if ($db && $collection) { 
  108.                  
  109.                 $this->_mongoDB = $_mongoDB->selectCollection($db, $collection); 
  110.             } else { 
  111.                 $this->_mongoDB = $_mongoDB->selectCollection($this->_db,$this->_collection); 
  112.             }*/  
  113.         } else {   
  114.             $this->_mongo = self::$_mongoObj[$key];  
  115.         }  
  116.     }  
  117.   
  118.     /** 
  119.      * Set Db & Collection 
  120.      * 重新设置数据库和数据表 
  121.      * @param string $db 
  122.      * @param string $collection 
  123.      */  
  124.     public function setDb($db = NULL, $collection = NULL)  
  125.     {  
  126.         if ($db) {  
  127.             $this->_db = $db;  
  128.             //$this->_mongoDB = NULL;  
  129.             //$this->_mongoDB = $this->_mongoObj->selectCollection($this->_db,$this->_collection);  
  130.         }  
  131.           
  132.         if ($collection) {  
  133.             $this->_collection = $collection;  
  134.         }  
  135.           
  136.         return $this;  
  137.     }  
  138.   
  139.     /** 
  140.      * Set Collection 
  141.      * 重新设置数据表 
  142.      * @param string $collection 
  143.      */  
  144.     public function setCollection($collection = NULL)  
  145.     {  
  146.         if ($collection) {  
  147.             $this->_collection = $collection;  
  148.             //$this->_mongoDB = NULL;  
  149.             //$this->_mongoDB = $this->_mongoObj->selectCollection($this->_db,$collection);  
  150.         }  
  151.           
  152.         return $this;  
  153.     }  
  154.     /** 
  155.      * 获取指定条件下的集合里的数据数量,默认使用_id主键字段 
  156.      */  
  157.     public function count($argv = array(),$fields = '_id')  
  158.     {  
  159.         $result = $this->find($argv,$fields);  
  160.           
  161.         if ($result) {  
  162.             return count($result);  
  163.         } else {  
  164.             return 0;  
  165.         }  
  166.     }  
  167.     /** 
  168.      * Fetch From Mongodb 
  169.      * 
  170.      * @param array $argv 
  171.      * @param number $skip 
  172.      * @param number $limit 
  173.      * @param array $sort 
  174.      * @return Ambigous <multitype:, multitype:>|boolean 
  175.      */  
  176.     public function find($argv = array(),$fields = array(),$sort = array(),$skip = 0, $limit = 0)  
  177.     {  
  178.         /*$argv = $this->validate($argv); 
  179.          
  180.         if ($argv) { 
  181.             $result = $this->_mongoDB->find($argv) 
  182.             ->skip($skip) 
  183.             ->limit($limit) 
  184.             ->sort($sort); 
  185.             return self::toArray($result); 
  186.         }*/  
  187.           
  188.         $options = array();  
  189.           
  190.         if ($skip) {  
  191.             $options['skip'] = $skip;  
  192.         }  
  193.           
  194.         if ($limit) {  
  195.             $options['limit'] = $limit;  
  196.         }  
  197.           
  198.         if ($sort) {  
  199.             $options['sort'] = $sort;  
  200.         }  
  201.           
  202.         if ($fields) {  
  203.             if (is_string($fields)) {  
  204.                 $fields = explode(','$fields);  
  205.             }  
  206.               
  207.             foreach ($fields as $v) {  
  208.                 $options['projection'][$v] = 1;  
  209.             }  
  210.         }   
  211.           
  212.         $query = new \MongoDB\Driver\Query($argv$options);   
  213.           
  214.         $cursor = $this->_mongo->executeQuery($this->_db.'.'.$this->_collection, $query);  
  215.       
  216.         return $cursor->toArray();  
  217.     }  
  218.     /** 
  219.      * 执行命令 
  220.      */  
  221.     public function runCommand($command = array())  
  222.     {  
  223.         if (!$command) {  
  224.             return false;  
  225.         }  
  226.           
  227.         $commandObj = new \MongoDB\Driver\Command($command);  
  228.           
  229.         try {  
  230.             $cursor = $this->_mongo->executeCommand($this->_db, $commandObj);  
  231.             $response = $cursor->toArray();  
  232.         } catch(\MongoDB\Driver\Exception $e) {  
  233.             echo 'Mongo的runCommand异常:',$e->getMessage();  
  234.             exit;  
  235.         }  
  236.           
  237.         if (count($response) > 1) {  
  238.             return $response;  
  239.         } else {  
  240.             return $response[0];  
  241.         }  
  242.     }  
  243.       
  244.     /** 
  245.      * Fetch By MongoId 
  246.      * 
  247.      * @param string $_id 
  248.      * @return Ambigous <Ambigous, boolean, multitype:> 
  249.      */  
  250.     public function findById($_id = '',$fields = array())  
  251.     {  
  252.         if (is_string($_id)) {  
  253.             return $this->findOne(array('_id' => new \MongoDB\BSON\ObjectID($_id)),$fields);  
  254.         }  
  255.     }  
  256.   
  257.     /** 
  258.      * Fetch One From MongoDB 
  259.      * 
  260.      * @param array $argv 
  261.      * @param array $fields 
  262.      * @return multitype: boolean 
  263.      */  
  264.     public function findOne($argv = array(),$fields = array(),$sort = array())  
  265.     {  
  266.         $result = $this->find($argv,$fields,$sort,0,1);  
  267.           
  268.         if ($result) {  
  269.             return $result[0];  
  270.         } else {  
  271.             return NULL;  
  272.         }  
  273.             //return $this->cleanId($this->_mongoDB->findOne($argv, $fields));  
  274.     }  
  275.   
  276.     /** 
  277.     * Update MongoDB By Id 
  278.     * 通过主键ID更新 
  279.     * @param string $_id 
  280.     * @param array $newData 
  281.     */  
  282.     public function updateById($_id$set = array())  
  283.     {  
  284.         return $this->updateStatement(array('_id' => new \MongoDB\BSON\ObjectID($_id)), array('$set'=>$set))->execute()->getModifiedCount();  
  285.     }  
  286.   
  287.     /** 
  288.     * 执行添加,删除,更新 All From Mongodb,执行多个语句 
  289.     * $obj->deleteStatement(array('name'=>'1'))->deleteStatement(array('id'=>1))->remove(); 
  290.     * @param array $argv 
  291.     */  
  292.     public function execute()  
  293.     {  
  294.         if (!$this->_sql) {  
  295.             return NULL;  
  296.         }  
  297.           
  298.         $bulk = new \MongoDB\Driver\BulkWrite;  
  299.           
  300.         foreach ($this->_sql as $val) {  
  301.             switch ($val['type']) {  
  302.                 case 'delete':  
  303.                     $bulk->delete($val['sql'],$val['limit']);  
  304.                     break;  
  305.                 case 'insert':  
  306.                     $bulk->insert($val['document']);  
  307.                     break;  
  308.                 case 'update':  
  309.                     $bulk->update($val['filter'],$val['set'],$val['options']);  
  310.                     break;  
  311.             }  
  312.               
  313.         }  
  314.           
  315.         $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);  
  316.           
  317.         try {  
  318.             $this->_exeResult = $this->_mongo->executeBulkWrite($this->_db.'.'.$this->_collection, $bulk$writeConcern);  
  319.         } catch(\MongoDB\Driver\Exception\WriteException $e) {  
  320.             echo 'MongoDB扩展写入异常:';  
  321.               
  322.             $writeResult = $e->getWriteResult();  
  323.               
  324.             if ($writeConcernError = $writeResult->getWriteConcernError()) {    
  325.                 echo $writeConcernError[0]->getMessage(),'<br />';  
  326.             }  
  327.               
  328.             if ($writeErrors = $writeResult->getWriteErrors()) {   
  329.                 echo $writeErrors[0]->getMessage();  
  330.             }  
  331.             exit();  
  332.         } catch (\MongoDB\Driver\Exception\InvalidArgumentException $e) {  
  333.             exit('MongoDB扩展传入参数异常:'.$e->getMessage());  
  334.         } catch (\MongoDB\Driver\Exception\RuntimeException $e) {  
  335.             exit('MongoDB扩展运行异常:'.$e->getMessage());  
  336.         } catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) {  
  337.             exit('MongoDB扩展运行超时异常:'.$e->getMessage());  
  338.         } catch (\MongoDB\Driver\Exception\ConnectionTimeoutException $e) {  
  339.             exit('MongoDB扩展连接超时异常:'.$e->getMessage());  
  340.         } catch (\Exception $e) {  
  341.             exit('系统异常:'.$e->getMessage());  
  342.         }  
  343.           
  344.         return $this;  
  345.     }  
  346.     /** 
  347.      * 获取删除的行数 
  348.      */  
  349.     public function getDeletedCount()  
  350.     {  
  351.         if ($this->_exeResult) {  
  352.             return $this->_exeResult->getDeletedCount();  
  353.         } else {  
  354.             return 0;  
  355.         }  
  356.     }  
  357.     /** 
  358.      * 获取实际更新的行数 
  359.      */  
  360.     public function getModifiedCount()  
  361.     {  
  362.         if ($this->_exeResult) {  
  363.             return $this->_exeResult->getModifiedCount();  
  364.         } else {  
  365.             return 0;  
  366.         }  
  367.     }  
  368.     /** 
  369.      * 一次最多插入9万条以下.耗时 
  370.      * 获取实际插入的行数 
  371.      */  
  372.     public function getInsertedCount()  
  373.     {  
  374.         if ($this->_exeResult) {  
  375.             return $this->_exeResult->getInsertedCount();  
  376.         } else {  
  377.             return 0;  
  378.         }  
  379.     }  
  380.     /** 
  381.      * 获取实际匹配的行数 
  382.      */  
  383.     public function getMatchedCount()  
  384.     {  
  385.         if ($this->_exeResult) {  
  386.             return $this->_exeResult->getMatchedCount();  
  387.         } else {  
  388.             return 0;  
  389.         }  
  390.     }  
  391.     /** 
  392.      * 获取实际更新失败然后新插入的行数 
  393.      *  
  394.      */  
  395.     public function getUpsertedCount()  
  396.     {  
  397.         if ($this->_exeResult) {  
  398.             return $this->_exeResult->getUpsertedCount();  
  399.         } else {  
  400.             return 0;  
  401.         }  
  402.     }  
  403.     /** 
  404.      * 获取实际更新失败然后新插入的ID列表 
  405.      */  
  406.     public function getUpsertedIds()  
  407.     {  
  408.         if ($this->_exeResult) {  
  409.             return $this->_exeResult->getUpsertedIds();  
  410.         } else {  
  411.             return 0;  
  412.         }  
  413.     }  
  414.        
  415.       
  416.     /** 
  417.      * delete子句 
  418.      * @param $delete 为删除过滤条件,为数组形式 
  419.      */  
  420.     public function deleteStatement($delete,$limit = 0)  
  421.     {  
  422.         $this->_sql[] = array('type'=>'delete','sql'=>$delete,'limit'=>array('limit'=>$limit));  
  423.           
  424.         return $this;  
  425.     }  
  426.     /** 
  427.      * insert子句 
  428.      * @param $batch 批量插入数据 
  429.      */  
  430.     public function insertStatement($insert,$batch = false)  
  431.     {  
  432.         if ($batch) {  
  433.             if (is_array($insert) && $insert) {  
  434.                 foreach ($insert as $val) {  
  435.                     $this->_sql[] = array('type'=>'insert','document'=>$val);   
  436.                 }  
  437.             }  
  438.         } else {  
  439.             $this->_sql[] = array('type'=>'insert','document'=>$insert);  
  440.         }  
  441.           
  442.         return $this;  
  443.     }  
  444.     /** 
  445.      * update子句 
  446.      * @param option multi 为true则更新全部符合条件的文档,否则只更新一个符合条件的文档 
  447.      *              upsert 为true则当没有符合条件的文档时将更新过后的数据插入到集合中 
  448.      * 参考连接:http://blog.csdn.net/qq1355541448/article/details/9082225 
  449.      * 第二个参数有以下的做法: 
  450.      *  修改更新   
  451.      *      使用set关键字: $set:让某节点等于给定值 ,字段不变,内容变了 
  452.      *  替换更新: 
  453.      *      第一个参数$where=array(‘column_name’=>’col709′),第二个参数:$newdata=array(‘column_exp’=>’HHHHHHHHH’,'column_fid’=>123); 
  454.      *      那么指定的column_name字段将会替换成成column_exp(=HHHHHHHHH)和column_fid(123) 
  455.      *  自动累加或自动累减 
  456.      *      array(‘$set’=>$newdata,’$inc’=>array(’91u’=>-5),第二个参数,在找到的91u字段的参数会自动在原值减5 
  457.      *  删除指定字段 
  458.      *      $where=array(‘column_name’=>’col685′); 
  459.      *      $result=$collection->update($where,array(‘$unset’=>’column_exp’));column_exp字段将会被删除 
  460.      * 参考文档:https://docs.mongodb.org/manual/reference/operator/update/ 
  461.      */  
  462.     public function updateStatement($filter,$set,$options = array('multi' => true, 'upsert' => false))  
  463.     {  
  464.         $this->_sql[] = array('type'=>'update','filter'=>$filter,'set'=>$set,'options'=>$options);  
  465.           
  466.         return $this;  
  467.     }  
  468.     /** 
  469.     * Remove By Id From Mongodb 
  470.     * 
  471.     * @param string $_id 
  472.     * @return Ambigous <boolean, multitype:> 
  473.     */  
  474.     public function removeById($_id)  
  475.     {  
  476.         return $this->deleteStatement(array('_id' => new \MongoDB\BSON\ObjectID($_id)))->execute()->getDeletedCount();  
  477.     }  
  478.   
  479.     /** 
  480.     * Remove One From Mongodb 
  481.     * 
  482.     * @param array $argv 
  483.     */  
  484.     public function removeOne($argv = array())  
  485.     {  
  486.         return $this->deleteStatement($argv,1)->execute()->getDeletedCount();  
  487.     }  
  488.   
  489.      /** 
  490.      * Remove Field From MongoDB 
  491.      * 
  492.      * @param string $_id 
  493.      * @param array $field 
  494.      */  
  495. //  public function removeFieldById($_id, $field = array())  
  496. //  {  
  497. //      return $this->updateStatement(array('_id' => new \MongoDB\BSON\ObjectID($_id)), array('$unset' => $unSetfield));  
  498. //  }  
  499.   
  500.     /** 
  501.     * Validate Data Callbak Function 没有用到的函数 
  502.     * 
  503.     * @param array $argv 
  504.      */  
  505.     private function validate($data)  
  506.     {  
  507.         if ($this->_validate) {  
  508.             foreach ($this->_validate as $arg => $validate) {  
  509.                 if (is_array($data) && array_key_exists(strval($arg), $data)) {  
  510.                     foreach ($validate as $key => $value) {  
  511.                         switch (strtolower($key)) {  
  512.                             case 'type':  
  513.                                 if ($value == 'int') {  
  514.                                     $data[$arg] = (int) $data[$arg];  
  515.                                 } elseif ($value == 'string') {  
  516.                                     $data[$arg] = (string) $data[$arg];  
  517.                                 } elseif ($value == 'bool') {  
  518.                                     $data[$arg] = (bool) $data[$arg];  
  519.                                 } elseif ($value == 'float') {  
  520.                                     $data[$arg] = (float) $data[$arg];  
  521.                                 } elseif ($value == 'array') {  
  522.                                     $data[$arg] = (array$data[$arg];  
  523.                                 }  
  524.                                 break;  
  525.                             case 'min':  
  526.                                 if (strlen($data[$arg]) < $value) {  
  527.                                     exit('Error: The length of ' . $arg . ' is not matched');  
  528.                                 }  
  529.                                 break;  
  530.                             case 'max':  
  531.                                 if (strlen($data[$arg]) > $value) {  
  532.                                     exit('Error: The length of ' . $arg . ' is not matched');  
  533.                                 }  
  534.                                 break;  
  535.                             case 'func':  
  536.                                 $call = preg_split('/[\:]+|\-\>/i'$value);  
  537.                                 if (count($call) == 1) {  
  538.                                     $data[$arg] = call_user_func($call['0'], $data[$arg]);  
  539.                                 } else {  
  540.                                     $data[$arg] = call_user_func_array(array($call['0'],$call['1']), array($data[$arg]));  
  541.                                 }  
  542.                                 break;  
  543.                         }  
  544.                     }  
  545.                 }  
  546.             }  
  547.         }  
  548.                               
  549.         return $data;  
  550.     }  
  551.     /** 
  552.      * mongdodb服务器的相关信息 
  553.      */  
  554.     public function buildInfo()  
  555.     {  
  556.         return $this->runCommand(array('buildinfo'=>1));  
  557.     }  
  558.     /** 
  559.      * 返回指定集合的统计信息,包括数据大小、已分配的存储空间和索引的大小。 
  560.      */  
  561.     public function collStats($collection = '')  
  562.     {  
  563.         if (!$collection) {  
  564.             $collection = $this->_collection;  
  565.               
  566.             if (!$collection) {  
  567.                 return NULL;  
  568.             }  
  569.         }  
  570.           
  571.         return $this->runCommand(array('collstats'=>$collection));  
  572.     }  
  573.     /** 
  574.      * 列出指定集合中满足查询条件的文档的指定键的所有不同值 
  575.      */  
  576.     public function distinct($field,$filter = array(),$collection = '')  
  577.     {  
  578.         if (!$collection) {  
  579.             $collection = $this->_collection;  
  580.               
  581.             if (!$collection) {  
  582.                 return NULL;  
  583.             }  
  584.         }  
  585.         return false;  
  586.         return $this->runCommand(array('key'=>$field,'query'=>$filter,'distinct'=>$collection));  
  587.     }  
  588.     /** 
  589.      * 删除集合的所有数据 
  590.      */  
  591.     public function drop($collection = '')  
  592.     {  
  593.         if (!$collection) {  
  594.             $collection = $this->_collection;  
  595.               
  596.             if (!$collection) {  
  597.                 return NULL;  
  598.             }  
  599.         }  
  600.           
  601.         return $this->runCommand(array('drop'=>$collection));  
  602.     }  
  603.     /** 
  604.      * 删除当前数据库中的所有数据 
  605.      */  
  606.     public function dropDatabase()  
  607.     {  
  608.         return $this->runCommand(array('dropdatabase'=>1));  
  609.     }  
  610.     /** 
  611.      * 删除集合里面名称为name的索引,如果名称为"*",则删除全部索引。 
  612.      */  
  613.     public function dropIndexes($index = '*',$collection = '')  
  614.     {  
  615.         if (!$collection) {  
  616.             $collection = $this->_collection;  
  617.               
  618.             if (!$collection) {  
  619.                 return NULL;  
  620.             }  
  621.         }  
  622.           
  623.         return $this->runCommand(array('dropIndexes'=>$collection,'index' => $index));  
  624.     }  
  625. //  /**  
  626. //   * 创建索引  
  627. //   */  
  628. //  public function createIndexes($index,$collection = '')  
  629. //  {  
  630. //      if (!$collection) {  
  631. //          $collection = $this->_collection;  
  632.                   
  633. //          if (!$collection) {  
  634. //              return NULL;  
  635. //          }  
  636. //      }  
  637.           
  638. //      return $this->runCommand(array('createIndexes'=>array('create'=>$collection),'index' => array('name'=>$index)));  
  639. //  }  
  640.     /** 
  641.      * 列出某个集合下所有的索引 
  642.      */  
  643.     public function listIndexes($collection = '')  
  644.     {  
  645.         if (!$collection) {  
  646.             $collection = $this->_collection;  
  647.           
  648.             if (!$collection) {  
  649.                 return NULL;  
  650.             }  
  651.         }  
  652.           
  653.         return $this->runCommand(array('listIndexes'=>$collection));  
  654.     }  
  655.     /** 
  656.      * 查找并修改 
  657.      */  
  658.     public function findAndModify($update = array(),$filter = array(),$collection = '')  
  659.     {  
  660.         if (!$collection) {  
  661.             $collection = $this->_collection;  
  662.               
  663.             if (!$collection) {  
  664.                 return NULL;  
  665.             }  
  666.         }  
  667.           
  668.         return $this->runCommand(array('findAndModify'=>$collection,'query' => $filter,'update'=>$update));  
  669.     }  
  670.     /** 
  671.      * 查看对本集合执行的最后一次操作的错误信息或者其它状态信息。在w台服务器复制集合的最后操作之前,这个命令会阻塞 
  672.      */  
  673.     public function getLastError()  
  674.     {  
  675.         return $this->runCommand(array('getLastError'=>1));  
  676.     }  
  677.     /** 
  678.      * 检查本服务器是主服务器还是从服务器 
  679.      */  
  680.     public function isMaster()  
  681.     {  
  682.         return $this->runCommand(array('ismaster'=>1));  
  683.     }  
  684.     /** 
  685.      * 返回所有可以在服务器上运行的命令及相关信息。 
  686.      */  
  687.     public function listCommands()  
  688.     {  
  689.         return $this->runCommand(array('listCommands'=>1));  
  690.     }  
  691.     /** 
  692.      * 管理专用命令,列出服务器上所有的数据库 
  693.      */  
  694.     public function listDatabases()  
  695.     {  
  696.         return $this->setDb('admin')->runCommand(array('listDatabases'=>1));  
  697.     }  
  698.     /** 
  699.      * 检查服务器链接是否正常。即便服务器上锁了,这条命令也会立刻返回 
  700.      */  
  701.     public function ping()  
  702.     {  
  703.         return $this->runCommand(array('ping'=>1));  
  704.     }  
  705.     /** 
  706.      * 将集合a重命名为b,其中a和b都必须是完整的集合命名空间(例如"test.foo"代表test数据库中的foo集合) 
  707.      * @param dropTarget Optional. If true, mongod will drop the target of renameCollection prior to renaming the collection. The default value is false. 
  708.      * 用法. $fromCollection = 'test.demo' , $toCollection = 'test.demo1' ,一定要加数据库前缀 
  709.      */  
  710.     public function renameCollection($fromCollection,$toCollection,$dropTarget = false)  
  711.     {  
  712.         if (!$fromCollection || !$toCollection) {  
  713.             return false;  
  714.         }  
  715.           
  716.         return $this->setDb('admin')->runCommand(array('renameCollection'=>$fromCollection,'to'=>$toCollection,'dropTarget'=>$dropTarget));  
  717.     }  
  718.     /** 
  719.      * 修复并压缩当前数据库,这个操作可能非常耗时。 
  720.      */  
  721.     public function repairDatabase()  
  722.     {  
  723.         return $this->setDb('admin')->runCommand(array('repairdatabase'=>1));  
  724.     }  
  725.     /** 
  726.      * 返回这台服务器的管理统计信息。 
  727.      */  
  728.     public function serverStatus()  
  729.     {  
  730.         return $this->runCommand(array('serverStatus'=>1));  
  731.     }  
  732.     /** 
  733.      * 创建集合 
  734.      * $options = array('autoIndexId','capped','size','max','flags'); 
  735.      */  
  736.     public function createCollection($collection,$options = array())  
  737.     {  
  738.         $options['create'] = $collection;  
  739.           
  740.         return $this->runCommand($options);  
  741.     }  
  742.     /** 
  743.      * 删除集合 
  744.      */  
  745.     public function dropCollection($collection)  
  746.     {  
  747.         if (!$collection) {  
  748.             return NULL;  
  749.         }  
  750.           
  751.         return $this->runCommand(array('drop'=>$collection));  
  752.     }  
  753. }  


部分用法如下:

  1. $config = array(  
  2.                 'mongo_seed1' => C('mongo_seed1'),  
  3.                 'mongo_seed2' => C('mongo_seed2'),  
  4.                 'mongo_replname' => C('mongo_replname'),  
  5.                 'mongo_user' => C('mongo_user'),  
  6.                 'mongo_pwd' => C('mongo_pwd')  
  7.         );  
  8.            
  9.         $mongoObj = new \Org\Util\TmongoDB($config,'demo','test');  
  10.           
  11.         $insert = array(  
  12.                 array(  
  13.                         'name'=> '走令敏',  
  14.                         'age'=> 24,  
  15.                         'address' => '江西省赣州市',  
  16.                         'gender' => '男',  
  17.                         'salary' => 5500  
  18.                 ),  
  19.                 array(  
  20.                         'name'=> '皇兄文',  
  21.                         'age'=> 24,  
  22.                         'address' => '江西省抚州市',  
  23.                         'gender' => '男',  
  24.                         'salary' => 6000  
  25.                 ),  
  26.                 array(  
  27.                         'name'=> '周李菲',  
  28.                         'age'=> 23,  
  29.                         'address' => '江西省上饶市',  
  30.                         'gender' => '男',  
  31.                         'salary' => 5000  
  32.                 ),  
  33.                 array(  
  34.                         'name'=> '主力科',  
  35.                         'age'=> 25,  
  36.                         'address' => '江西省上饶市',  
  37.                         'gender' => '男',  
  38.                         'salary' => 1000  
  39.                 ),  
  40.                 array(  
  41.                         'name'=> '夜舟',  
  42.                         'age'=> 25,  
  43.                         'address' => '江西省上饶市',  
  44.                         'gender' => '男',  
  45.                         'salary' => 7000  
  46.                 ),  
  47.                 array(  
  48.                         'name'=> '周倩倩',  
  49.                         'age'=> 23,  
  50.                         'address' => '江西省上饶市',  
  51.                         'gender' => '女',  
  52.                         'salary' => 7000  
  53.                 ),  
  54.                 array(  
  55.                         'name'=> '网点保',  
  56.                         'age'=> 22,  
  57.                         'address' => '河南省鹤壁市',  
  58.                         'gender' => '男',  
  59.                         'salary' => 10000  
  60.                 ),  
  61.                 array(  
  62.                         'name'=> '舒玉婷',  
  63.                         'age'=> 24,  
  64.                         'address' => '江西省上饶市',  
  65.                         'gender' => '女',  
  66.                         'salary' => 6000  
  67.                 ),  
  68.                 array(  
  69.                         'name'=> '少见波',  
  70.                         'age'=> 27,  
  71.                         'address' => '辽宁省吉林市',  
  72.                         'gender' => '男',  
  73.                         'salary' => 20000  
  74.                 ),  
  75.                 array(  
  76.                         'name'=> '李存平',  
  77.                         'age'=> 25,  
  78.                         'address' => '江西省吉安市',  
  79.                         'gender' => '男',  
  80.                         'salary' => 6000  
  81.                 )  
  82.         );  
  83.   
  84.         $arr = array();  
  85.   
  86.         for ($i = 0;$i < 10;++$i) {  
  87.             for ($j = 0;$j < 10;++$j) {  
  88.                 $key = $i*10 + $j;  
  89.                 $arr[$key] = $insert[$j];  
  90.                 $arr[$key]['num'] = $key;  
  91.                 $arr[$key]['_id'] = new \MongoDB\BSon\ObjectID;  
  92.             }  
  93.         }  
  94.            
  95.         $starttime = microtime(true);  
  96.         $result = $mongoObj->insertStatement($arr,true)->execute()->getInsertedCount();;  
  97.         $endtime = microtime(true);  
  98.         echo '执行时间:',($endtime - $starttime),'秒<br />';  
  99.         echo $result;  
  100.       
  101.         echo 'ping';  
  102.         // 查询所有的记录  
  103.         $result = $mongoObj->runCommand(array('ping'=>1));  
  104.         dump($result);  
  105.           
  106.         echo '<br/>,getLastError';  
  107.         $error = $mongoObj->getLastError();  
  108.           
  109.         dump($error);  
  110.           
  111.         $result = $mongoObj->buildInfo();  
  112.           
  113.         echo '<br/>,buildInfo';  
  114.         dump($result);  
  115.           
  116.         $result = $mongoObj->collStats('test');  
  117.           
  118.         echo '<br/>,collStats';  
  119.         dump($result);  
  120.           
  121.         $result = $mongoObj->distinct('salary',array('num'=>array('$gt'=>20)));  
  122.           
  123.         echo '<br />,distinct';  
  124.           
  125.         dump($result);  
  126.           
  127.         $result = $mongoObj->isMaster();  
  128.           
  129.         echo '<br />,isMaster';  
  130.         dump($result);  
  131.           
  132.         $result = $mongoObj->listCommands();  
  133.           
  134.         echo '<br/>,listCommands';  
  135.           
  136.         dump($result);  
  137.           
  138.         $result = $mongoObj->listDatabases();  
  139.         echo '<br/>,listDatabases';  
  140.            
  141.         dump($result);  
  142.            
  143.         $result = $mongoObj->serverStatus();  
  144.         echo '<br/>,serverStatus';  
  145.           
  146.         dump($result);  
  147.         $result = $mongoObj->renameCollection('demo.hello''demo.hello123');  
  148.         echo '<br/>,renameCollection';  
  149.            
  150.         dump($result);  
  151.           
  152.         $result = $mongoObj->createCollection('ceshi');  
  153.         echo '<br/>,createCollection';  
  154.           
  155.         dump($result);  
  156.         $result = $mongoObj->dropCollection('demo1');  
  157.           
  158.         echo '<br />,dropCollection';  
  159.         dump($result);  


来源:http://blog.csdn.net/zhulike2011/article/details/50422391

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值