生活随笔
收集整理的這篇文章主要介紹了
MongoDB for PHP扩展操作类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<?php????????????????????class?TmongoDB??{????????protected?$_db?=?'test';????????protected?$_collection?=?'user';????????protected?$_validate?=?array();????????protected?static?$_mongoObj?=?array();????????????private?$_exeResult?=?null;??????protected?$_sql?=?array();????????????protected?$_mongo?=?null;?????????????const?CONNECT_DB?=?'admin';???????????????????????protected?$_config?=?array(??????????????'mongo_seed1'?=>?'localhost',??????????????'mongo_seed2'?=>?'',??????????????'mongo_replname'?=>?'',??????????????'mongo_user'?=>?NULL,??????????????'mongo_pwd'?=>?NULL??????);????????public?function?__construct($config,$db,?$collection)??????{??????????foreach?($this->_config?as?$k?=>?$v)?{??????????????if(isset($config[$k])){??????????????????$this->_config[$k]?=?$config[$k];??????????????}?else?{??????????????????E('mongoDB數據庫連接,請傳遞'.$k);??????????????}??????????}????????????$this->_db?=?$db;??????????$this->_collection?=?$collection;????????????????????$this->init();??????}????????????public?function?getMongo()??????{??????????return?$this->_mongo;??????}???????????????????????public?function?init()??????{??????????$config?=?$this->_config;??????????ksort($config);??????????$encryptStr?=?'';?????????????????????foreach?($config?as?$k?=>?$v)?{??????????????$encryptStr?.=?($k.$v);??????????}????????????????????$key?=?md5($encryptStr);????????????????????if?(!self::$_mongoObj[$key])?{??????????????????????????????????????$demo_uri?=?'mongodb://'?.?$config['mongo_user']?.?':'?.?$config['mongo_pwd']?.?'@'?.??????????????????????$config['mongo_seed1']?.?','?.?$config['mongo_seed2']?.?'/'?.?self::CONNECT_DB?.?'?replicaSet='?.?$config['mongo_replname'];?????????????????????????$manager?=?new?\MongoDB\Driver\Manager($demo_uri);????????????????????????????self::$_mongoObj[$key]?=?$this->_mongo?=?$manager;????????????????????????????????????????????}?else?{???????????????$this->_mongo?=?self::$_mongoObj[$key];??????????}??????}???????????????????public?function?setDb($db?=?NULL,?$collection?=?NULL)??????{??????????if?($db)?{??????????????$this->_db?=?$db;??????????????????????????????????????}????????????????????if?($collection)?{??????????????$this->_collection?=?$collection;??????????}????????????????????return?$this;??????}??????????????????public?function?setCollection($collection?=?NULL)??????{??????????if?($collection)?{??????????????$this->_collection?=?$collection;??????????????????????????????????????}????????????????????return?$this;??????}??????????????public?function?count($argv?=?array(),$fields?=?'_id')??????{??????????$result?=?$this->find($argv,$fields);????????????????????if?($result)?{??????????????return?count($result);??????????}?else?{??????????????return?0;??????????}??????}????????????????????public?function?find($argv?=?array(),$fields?=?array(),$sort?=?array(),$skip?=?0,?$limit?=?0)??????{??????????????????????????????????????$options?=?array();????????????????????if?($skip)?{??????????????$options['skip']?=?$skip;??????????}????????????????????if?($limit)?{??????????????$options['limit']?=?$limit;??????????}????????????????????if?($sort)?{??????????????$options['sort']?=?$sort;??????????}????????????????????if?($fields)?{??????????????if?(is_string($fields))?{??????????????????$fields?=?explode(',',?$fields);??????????????}????????????????????????????foreach?($fields?as?$v)?{??????????????????$options['projection'][$v]?=?1;??????????????}??????????}?????????????????????$query?=?new?\MongoDB\Driver\Query($argv,?$options);?????????????????????$cursor?=?$this->_mongo->executeQuery($this->_db.'.'.$this->_collection,?$query);????????????????return?$cursor->toArray();??????}??????????????public?function?runCommand($command?=?array())??????{??????????if?(!$command)?{??????????????return?false;??????????}????????????????????$commandObj?=?new?\MongoDB\Driver\Command($command);????????????????????try?{??????????????$cursor?=?$this->_mongo->executeCommand($this->_db,?$commandObj);??????????????$response?=?$cursor->toArray();??????????}?catch(\MongoDB\Driver\Exception?$e)?{??????????????echo?'Mongo的runCommand異常:',$e->getMessage();??????????????exit;??????????}????????????????????if?(count($response)?>?1)?{??????????????return?$response;??????????}?else?{??????????????return?$response[0];??????????}??????}???????????????????????public?function?findById($_id?=?'',$fields?=?array())??????{??????????if?(is_string($_id))?{??????????????return?$this->findOne(array('_id'?=>?new?\MongoDB\BSON\ObjectID($_id)),$fields);??????????}??????}????????????????????public?function?findOne($argv?=?array(),$fields?=?array(),$sort?=?array())??????{??????????$result?=?$this->find($argv,$fields,$sort,0,1);????????????????????if?($result)?{??????????????return?$result[0];??????????}?else?{??????????????return?NULL;??????????}????????????????????}???????????????????public?function?updateById($_id,?$set?=?array())??????{??????????return?$this->updateStatement(array('_id'?=>?new?\MongoDB\BSON\ObjectID($_id)),?array('$set'=>$set))->execute()->getModifiedCount();??????}??????????????????public?function?execute()??????{??????????if?(!$this->_sql)?{??????????????return?NULL;??????????}????????????????????$bulk?=?new?\MongoDB\Driver\BulkWrite;????????????????????foreach?($this->_sql?as?$val)?{??????????????switch?($val['type'])?{??????????????????case?'delete':??????????????????????$bulk->delete($val['sql'],$val['limit']);??????????????????????break;??????????????????case?'insert':??????????????????????$bulk->insert($val['document']);??????????????????????break;??????????????????case?'update':??????????????????????$bulk->update($val['filter'],$val['set'],$val['options']);??????????????????????break;??????????????}????????????????????????}????????????????????$writeConcern?=?new?\MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY,?1000);????????????????????try?{??????????????$this->_exeResult?=?$this->_mongo->executeBulkWrite($this->_db.'.'.$this->_collection,?$bulk,?$writeConcern);??????????}?catch(\MongoDB\Driver\Exception\WriteException?$e)?{??????????????echo?'MongoDB擴展寫入異常:';????????????????????????????$writeResult?=?$e->getWriteResult();????????????????????????????if?($writeConcernError?=?$writeResult->getWriteConcernError())?{????????????????????echo?$writeConcernError[0]->getMessage(),'<br?/>';??????????????}????????????????????????????if?($writeErrors?=?$writeResult->getWriteErrors())?{???????????????????echo?$writeErrors[0]->getMessage();??????????????}??????????????exit();??????????}?catch?(\MongoDB\Driver\Exception\InvalidArgumentException?$e)?{??????????????exit('MongoDB擴展傳入參數異常:'.$e->getMessage());??????????}?catch?(\MongoDB\Driver\Exception\RuntimeException?$e)?{??????????????exit('MongoDB擴展運行異常:'.$e->getMessage());??????????}?catch?(\MongoDB\Driver\Exception\ExecutionTimeoutException?$e)?{??????????????exit('MongoDB擴展運行超時異常:'.$e->getMessage());??????????}?catch?(\MongoDB\Driver\Exception\ConnectionTimeoutException?$e)?{??????????????exit('MongoDB擴展連接超時異常:'.$e->getMessage());??????????}?catch?(\Exception?$e)?{??????????????exit('系統異常:'.$e->getMessage());??????????}????????????????????return?$this;??????}??????????????public?function?getDeletedCount()??????{??????????if?($this->_exeResult)?{??????????????return?$this->_exeResult->getDeletedCount();??????????}?else?{??????????????return?0;??????????}??????}??????????????public?function?getModifiedCount()??????{??????????if?($this->_exeResult)?{??????????????return?$this->_exeResult->getModifiedCount();??????????}?else?{??????????????return?0;??????????}??????}???????????????public?function?getInsertedCount()??????{??????????if?($this->_exeResult)?{??????????????return?$this->_exeResult->getInsertedCount();??????????}?else?{??????????????return?0;??????????}??????}??????????????public?function?getMatchedCount()??????{??????????if?($this->_exeResult)?{??????????????return?$this->_exeResult->getMatchedCount();??????????}?else?{??????????????return?0;??????????}??????}???????????????public?function?getUpsertedCount()??????{??????????if?($this->_exeResult)?{??????????????return?$this->_exeResult->getUpsertedCount();??????????}?else?{??????????????return?0;??????????}??????}??????????????public?function?getUpsertedIds()??????{??????????if?($this->_exeResult)?{??????????????return?$this->_exeResult->getUpsertedIds();??????????}?else?{??????????????return?0;??????????}??????}????????????????????????????public?function?deleteStatement($delete,$limit?=?0)??????{??????????$this->_sql[]?=?array('type'=>'delete','sql'=>$delete,'limit'=>array('limit'=>$limit));????????????????????return?$this;??????}???????????????public?function?insertStatement($insert,$batch?=?false)??????{??????????if?($batch)?{??????????????if?(is_array($insert)?&&?$insert)?{??????????????????foreach?($insert?as?$val)?{??????????????????????$this->_sql[]?=?array('type'=>'insert','document'=>$val);???????????????????}??????????????}??????????}?else?{??????????????$this->_sql[]?=?array('type'=>'insert','document'=>$insert);??????????}????????????????????return?$this;??????}?????????????????????????????public?function?updateStatement($filter,$set,$options?=?array('multi'?=>?true,?'upsert'?=>?false))??????{??????????$this->_sql[]?=?array('type'=>'update','filter'=>$filter,'set'=>$set,'options'=>$options);????????????????????return?$this;??????}?????????????????public?function?removeById($_id)??????{??????????return?$this->deleteStatement(array('_id'?=>?new?\MongoDB\BSON\ObjectID($_id)))->execute()->getDeletedCount();??????}??????????????????public?function?removeOne($argv?=?array())??????{??????????return?$this->deleteStatement($argv,1)->execute()->getDeletedCount();??????}????????????????????????????????????????private?function?validate($data)??????{??????????if?($this->_validate)?{??????????????foreach?($this->_validate?as?$arg?=>?$validate)?{??????????????????if?(is_array($data)?&&?array_key_exists(strval($arg),?$data))?{??????????????????????foreach?($validate?as?$key?=>?$value)?{??????????????????????????switch?(strtolower($key))?{??????????????????????????????case?'type':??????????????????????????????????if?($value?==?'int')?{??????????????????????????????????????$data[$arg]?=?(int)?$data[$arg];??????????????????????????????????}?elseif?($value?==?'string')?{??????????????????????????????????????$data[$arg]?=?(string)?$data[$arg];??????????????????????????????????}?elseif?($value?==?'bool')?{??????????????????????????????????????$data[$arg]?=?(bool)?$data[$arg];??????????????????????????????????}?elseif?($value?==?'float')?{??????????????????????????????????????$data[$arg]?=?(float)?$data[$arg];??????????????????????????????????}?elseif?($value?==?'array')?{??????????????????????????????????????$data[$arg]?=?(array)?$data[$arg];??????????????????????????????????}??????????????????????????????????break;??????????????????????????????case?'min':??????????????????????????????????if?(strlen($data[$arg])?<?$value)?{??????????????????????????????????????exit('Error:?The?length?of?'?.?$arg?.?'?is?not?matched');??????????????????????????????????}??????????????????????????????????break;??????????????????????????????case?'max':??????????????????????????????????if?(strlen($data[$arg])?>?$value)?{??????????????????????????????????????exit('Error:?The?length?of?'?.?$arg?.?'?is?not?matched');??????????????????????????????????}??????????????????????????????????break;??????????????????????????????case?'func':??????????????????????????????????$call?=?preg_split('/[\:]+|\-\>/i',?$value);??????????????????????????????????if?(count($call)?==?1)?{??????????????????????????????????????$data[$arg]?=?call_user_func($call['0'],?$data[$arg]);??????????????????????????????????}?else?{??????????????????????????????????????$data[$arg]?=?call_user_func_array(array($call['0'],$call['1']),?array($data[$arg]));??????????????????????????????????}??????????????????????????????????break;??????????????????????????}??????????????????????}??????????????????}??????????????}??????????}????????????????????????????????????????return?$data;??????}??????????????public?function?buildInfo()??????{??????????return?$this->runCommand(array('buildinfo'=>1));??????}??????????????public?function?collStats($collection?=?'')??????{??????????if?(!$collection)?{??????????????$collection?=?$this->_collection;????????????????????????????if?(!$collection)?{??????????????????return?NULL;??????????????}??????????}????????????????????return?$this->runCommand(array('collstats'=>$collection));??????}??????????????public?function?distinct($field,$filter?=?array(),$collection?=?'')??????{??????????if?(!$collection)?{??????????????$collection?=?$this->_collection;????????????????????????????if?(!$collection)?{??????????????????return?NULL;??????????????}??????????}??????????return?false;??????????return?$this->runCommand(array('key'=>$field,'query'=>$filter,'distinct'=>$collection));??????}??????????????public?function?drop($collection?=?'')??????{??????????if?(!$collection)?{??????????????$collection?=?$this->_collection;????????????????????????????if?(!$collection)?{??????????????????return?NULL;??????????????}??????????}????????????????????return?$this->runCommand(array('drop'=>$collection));??????}??????????????public?function?dropDatabase()??????{??????????return?$this->runCommand(array('dropdatabase'=>1));??????}??????????????public?function?dropIndexes($index?=?'*',$collection?=?'')??????{??????????if?(!$collection)?{??????????????$collection?=?$this->_collection;????????????????????????????if?(!$collection)?{??????????????????return?NULL;??????????????}??????????}????????????????????return?$this->runCommand(array('dropIndexes'=>$collection,'index'?=>?$index));??????}????????????????????????????????????????????????????????????????????public?function?listIndexes($collection?=?'')??????{??????????if?(!$collection)?{??????????????$collection?=?$this->_collection;????????????????????????if?(!$collection)?{??????????????????return?NULL;??????????????}??????????}????????????????????return?$this->runCommand(array('listIndexes'=>$collection));??????}??????????????public?function?findAndModify($update?=?array(),$filter?=?array(),$collection?=?'')??????{??????????if?(!$collection)?{??????????????$collection?=?$this->_collection;????????????????????????????if?(!$collection)?{??????????????????return?NULL;??????????????}??????????}????????????????????return?$this->runCommand(array('findAndModify'=>$collection,'query'?=>?$filter,'update'=>$update));??????}??????????????public?function?getLastError()??????{??????????return?$this->runCommand(array('getLastError'=>1));??????}??????????????public?function?isMaster()??????{??????????return?$this->runCommand(array('ismaster'=>1));??????}??????????????public?function?listCommands()??????{??????????return?$this->runCommand(array('listCommands'=>1));??????}??????????????public?function?listDatabases()??????{??????????return?$this->setDb('admin')->runCommand(array('listDatabases'=>1));??????}??????????????public?function?ping()??????{??????????return?$this->runCommand(array('ping'=>1));??????}????????????????public?function?renameCollection($fromCollection,$toCollection,$dropTarget?=?false)??????{??????????if?(!$fromCollection?||?!$toCollection)?{??????????????return?false;??????????}????????????????????return?$this->setDb('admin')->runCommand(array('renameCollection'=>$fromCollection,'to'=>$toCollection,'dropTarget'=>$dropTarget));??????}??????????????public?function?repairDatabase()??????{??????????return?$this->setDb('admin')->runCommand(array('repairdatabase'=>1));??????}??????????????public?function?serverStatus()??????{??????????return?$this->runCommand(array('serverStatus'=>1));??????}???????????????public?function?createCollection($collection,$options?=?array())??????{??????????$options['create']?=?$collection;????????????????????return?$this->runCommand($options);??????}??????????????public?function?dropCollection($collection)??????{??????????if?(!$collection)?{??????????????return?NULL;??????????}????????????????????return?$this->runCommand(array('drop'=>$collection));??????}??}??
部分用法如下:
[php] view plain
copy $config?=?array(??????????????????'mongo_seed1'?=>?C('mongo_seed1'),??????????????????'mongo_seed2'?=>?C('mongo_seed2'),??????????????????'mongo_replname'?=>?C('mongo_replname'),??????????????????'mongo_user'?=>?C('mongo_user'),??????????????????'mongo_pwd'?=>?C('mongo_pwd')??????????);?????????????????????$mongoObj?=?new?\Org\Util\TmongoDB($config,'demo','test');????????????????????$insert?=?array(??????????????????array(??????????????????????????'name'=>?'走令敏',??????????????????????????'age'=>?24,??????????????????????????'address'?=>?'江西省贛州市',??????????????????????????'gender'?=>?'男',??????????????????????????'salary'?=>?5500??????????????????),??????????????????array(??????????????????????????'name'=>?'皇兄文',??????????????????????????'age'=>?24,??????????????????????????'address'?=>?'江西省撫州市',??????????????????????????'gender'?=>?'男',??????????????????????????'salary'?=>?6000??????????????????),??????????????????array(??????????????????????????'name'=>?'周李菲',??????????????????????????'age'=>?23,??????????????????????????'address'?=>?'江西省上饒市',??????????????????????????'gender'?=>?'男',??????????????????????????'salary'?=>?5000??????????????????),??????????????????array(??????????????????????????'name'=>?'主力科',??????????????????????????'age'=>?25,??????????????????????????'address'?=>?'江西省上饒市',??????????????????????????'gender'?=>?'男',??????????????????????????'salary'?=>?1000??????????????????),??????????????????array(??????????????????????????'name'=>?'夜舟',??????????????????????????'age'=>?25,??????????????????????????'address'?=>?'江西省上饒市',??????????????????????????'gender'?=>?'男',??????????????????????????'salary'?=>?7000??????????????????),??????????????????array(??????????????????????????'name'=>?'周倩倩',??????????????????????????'age'=>?23,??????????????????????????'address'?=>?'江西省上饒市',??????????????????????????'gender'?=>?'女',??????????????????????????'salary'?=>?7000??????????????????),??????????????????array(??????????????????????????'name'=>?'網點保',??????????????????????????'age'=>?22,??????????????????????????'address'?=>?'河南省鶴壁市',??????????????????????????'gender'?=>?'男',??????????????????????????'salary'?=>?10000??????????????????),??????????????????array(??????????????????????????'name'=>?'舒玉婷',??????????????????????????'age'=>?24,??????????????????????????'address'?=>?'江西省上饒市',??????????????????????????'gender'?=>?'女',??????????????????????????'salary'?=>?6000??????????????????),??????????????????array(??????????????????????????'name'=>?'少見波',??????????????????????????'age'=>?27,??????????????????????????'address'?=>?'遼寧省吉林市',??????????????????????????'gender'?=>?'男',??????????????????????????'salary'?=>?20000??????????????????),??????????????????array(??????????????????????????'name'=>?'李存平',??????????????????????????'age'=>?25,??????????????????????????'address'?=>?'江西省吉安市',??????????????????????????'gender'?=>?'男',??????????????????????????'salary'?=>?6000??????????????????)??????????);????????????$arr?=?array();????????????for?($i?=?0;$i?<?10;++$i)?{??????????????for?($j?=?0;$j?<?10;++$j)?{??????????????????$key?=?$i*10?+?$j;??????????????????$arr[$key]?=?$insert[$j];??????????????????$arr[$key]['num']?=?$key;??????????????????$arr[$key]['_id']?=?new?\MongoDB\BSon\ObjectID;??????????????}??????????}?????????????????????$starttime?=?microtime(true);??????????$result?=?$mongoObj->insertStatement($arr,true)->execute()->getInsertedCount();;??????????$endtime?=?microtime(true);??????????echo?'執行時間:',($endtime?-?$starttime),'秒<br?/>';??????????echo?$result;????????????????echo?'ping';????????????????????$result?=?$mongoObj->runCommand(array('ping'=>1));??????????dump($result);????????????????????echo?'<br/>,getLastError';??????????$error?=?$mongoObj->getLastError();????????????????????dump($error);????????????????????$result?=?$mongoObj->buildInfo();????????????????????echo?'<br/>,buildInfo';??????????dump($result);????????????????????$result?=?$mongoObj->collStats('test');????????????????????echo?'<br/>,collStats';??????????dump($result);????????????????????$result?=?$mongoObj->distinct('salary',array('num'=>array('$gt'=>20)));????????????????????echo?'<br?/>,distinct';????????????????????dump($result);????????????????????$result?=?$mongoObj->isMaster();????????????????????echo?'<br?/>,isMaster';??????????dump($result);????????????????????$result?=?$mongoObj->listCommands();????????????????????echo?'<br/>,listCommands';????????????????????dump($result);????????????????????$result?=?$mongoObj->listDatabases();??????????echo?'<br/>,listDatabases';?????????????????????dump($result);?????????????????????$result?=?$mongoObj->serverStatus();??????????echo?'<br/>,serverStatus';????????????????????dump($result);??????????$result?=?$mongoObj->renameCollection('demo.hello',?'demo.hello123');??????????echo?'<br/>,renameCollection';?????????????????????dump($result);????????????????????$result?=?$mongoObj->createCollection('ceshi');??????????echo?'<br/>,createCollection';????????????????????dump($result);??????????$result?=?$mongoObj->dropCollection('demo1');????????????????????echo?'<br?/>,dropCollection';??????????dump($result);??
來源:http://blog.csdn.net/zhulike2011/article/details/50422391
總結
以上是生活随笔為你收集整理的MongoDB for PHP扩展操作类的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。