php封装的mongodb操作类代码
核心代码
error("TheMongoDBPECLextensionhasnotbeeninstalledorenabled",500); } $configs=wxcity_base::load_config("cache","mongo_db"); $num=count($configs['connect']); $this->timeout=trim($configs['timeout']); $keys=wxcity_base::load_config('double'); $this->key=$keys['mongo_db']; $this->config=$configs['connect'][$this->key]; $status=$this->connect(); if($status==false) { for($i=1;$i<$num;$i++) { $n=$this->key+$i; $key=$n>=$num?$n-$num:$n; $this->config=$configs['connect'][$key]; $status=$this->connect(); if($status!=false) { $keys['mongo_db']=$key; $this->key=$key; $data=""; file_put_contents(WHTY_PATH.'configs/double.php',$data,LOCK_EX); break; } } } if($status==false) { die('mongoDBnotconnect'); } } function__destruct(){ if((IS_NOSQL!=1)){ return; } if($this->connection) { $this->connection->close(); } } /***--------------------------------------------------------------------------------*CONNECTTOMONGODB*--------------------------------------------------------------------------------**EstablishaconnectiontoMongoDBusingtheconnectionstringgeneratedin*theconnection_string()method.If'mongo_persist_key'wassettotrueinthe*configfile,establishapersistentconnection.Weallowforonlythe'persist'*optiontobesetbecausewewanttoestablishaconnectionimmediately.*/ privatefunctionconnect(){ $this->connection_string(); $options=array('connect'=>true,'timeout'=>$this->timeout); try{ $this->connection=newMongo($this->connection_string,$options); $this->db=$this->connection->{$this->dbname}; return($this); }catch(MongoConnectionException$e){ returnfalse; } } /***--------------------------------------------------------------------------------*BUILDCONNECTIONSTRING*--------------------------------------------------------------------------------**Buildtheconnectionstringfromtheconfigfile.*/ privatefunctionconnection_string(){ $this->host=trim($this->config['hostname']); $this->port=trim($this->config['port']); $this->user=trim($this->config['username']); $this->pass=trim($this->config['password']); $this->dbname=trim($this->config['database']); $this->persist=trim($this->config['autoconnect']); $this->persist_key=trim($this->config['mongo_persist_key']); $connection_string="mongodb://"; if(emptyempty($this->host)){ $this->error("TheHostmustbesettoconnecttoMongoDB",500); }if(emptyempty($this->dbname)){ $this->error("TheDatabasemustbesettoconnecttoMongoDB",500); }if(!emptyempty($this->user)&&!emptyempty($this->pass)){ $connection_string.="{$this->user}:{$this->pass}@"; }if(isset($this->port)&&!emptyempty($this->port)){ $connection_string.="{$this->host}:{$this->port}"; }else{ $connection_string.="{$this->host}"; }$this->connection_string=trim($connection_string); } /***--------------------------------------------------------------------------------*Switch_db*--------------------------------------------------------------------------------**Switchfromdefaultdatabasetoadifferentdb*/ publicfunctionswitch_db($database=''){ if(emptyempty($database)){ $this->error("ToswitchMongoDBdatabases,anewdatabasenamemustbespecified",500); }$this->dbname=$database; try{ $this->db=$this->connection->{$this->dbname}; return(TRUE); }catch(Exception$e){ $this->error("UnabletoswitchMongoDatabases:{$e->getMessage()}",500); } } /***--------------------------------------------------------------------------------*SELECTFIELDS*--------------------------------------------------------------------------------**DeterminewhichfieldstoincludeORwhichtoexcludeduringthequeryprocess.*Currently,includingandexcludingatthesametimeisnotavailable,sothe*$includesarraywilltakeprecedenceoverthe$excludesarray.Ifyouwantto*onlychoosefieldstoexclude,leave$includesanemptyarray().**@usage:$this->mongo_db->select(array('foo','bar'))->get('foobar');*/ publicfunctionselect($includes=array(),$excludes=array()){ if(!is_array($includes)){ $includes=array(); } if(!is_array($excludes)){ $excludes=array(); } if(!emptyempty($includes)){ foreach($includesas$col){ $this->selects[$col]=1; } }else{ foreach($excludesas$col){ $this->selects[$col]=0; } }return($this); } /***--------------------------------------------------------------------------------*WHEREPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentsbasedonthesesearchparameters.The$wheresarrayshould*beanassociativearraywiththefieldasthekeyandthevalueasthesearch*criteria.**@usage=$this->mongo_db->where(array('foo'=>'bar'))->get('foobar');*/ publicfunctionwhere($wheres=array()){ foreach((array)$wheresas$wh=>$val){ $this->wheres[$wh]=$val; }return($this); } /***--------------------------------------------------------------------------------*WHERE_INPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentswherethevalueofa$fieldisinagiven$inarray().**@usage=$this->mongo_db->where_in('foo',array('bar','zoo','blah'))->get('foobar');*/ publicfunctionwhere_in($field="",$in=array()){ $this->where_init($field); $this->wheres[$field]['$in']=$in; return($this); } /***--------------------------------------------------------------------------------*WHERE_NOT_INPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentswherethevalueofa$fieldisnotinagiven$inarray().**@usage=$this->mongo_db->where_not_in('foo',array('bar','zoo','blah'))->get('foobar');*/ publicfunctionwhere_not_in($field="",$in=array()){ $this->where_init($field); $this->wheres[$field]['$nin']=$in; return($this); } /***--------------------------------------------------------------------------------*WHEREGREATERTHANPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentswherethevalueofa$fieldisgreaterthan$x**@usage=$this->mongo_db->where_gt('foo',20);*/ publicfunctionwhere_gt($field="",$x){ $this->where_init($field); $this->wheres[$field]['$gt']=$x; return($this); } /***--------------------------------------------------------------------------------*WHEREGREATERTHANOREQUALTOPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentswherethevalueofa$fieldisgreaterthanorequalto$x**@usage=$this->mongo_db->where_gte('foo',20);*/ publicfunctionwhere_gte($field="",$x){ $this->where_init($field); $this->wheres[$field]['$gte']=$x; return($this); } /***--------------------------------------------------------------------------------*WHERELESSTHANPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentswherethevalueofa$fieldislessthan$x**@usage=$this->mongo_db->where_lt('foo',20);*/ publicfunctionwhere_lt($field="",$x){ $this->where_init($field); $this->wheres[$field]['$lt']=$x; return($this); } /***--------------------------------------------------------------------------------*WHERELESSTHANOREQUALTOPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentswherethevalueofa$fieldislessthanorequalto$x**@usage=$this->mongo_db->where_lte('foo',20);*/ publicfunctionwhere_lte($field="",$x){ $this->where_init($field); $this->wheres[$field]['$lte']=$x; return($this); } /***--------------------------------------------------------------------------------*WHEREBETWEENPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentswherethevalueofa$fieldisbetween$xand$y**@usage=$this->mongo_db->where_between('foo',20,30);*/ publicfunctionwhere_between($field="",$x,$y){ $this->where_init($field); $this->wheres[$field]['$gte']=$x; $this->wheres[$field]['$lte']=$y; return($this); } /***--------------------------------------------------------------------------------*WHEREBETWEENANDNOTEQUALTOPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentswherethevalueofa$fieldisbetweenbutnotequalto$xand$y**@usage=$this->mongo_db->where_between_ne('foo',20,30);*/ publicfunctionwhere_between_ne($field="",$x,$y){ $this->where_init($field); $this->wheres[$field]['$gt']=$x; $this->wheres[$field]['$lt']=$y; return($this); } /***--------------------------------------------------------------------------------*WHERENOTEQUALTOPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentswherethevalueofa$fieldisnotequalto$x**@usage=$this->mongo_db->where_between('foo',20,30);*/ publicfunctionwhere_ne($field="",$x){ $this->where_init($field); $this->wheres[$field]['$ne']=$x; return($this); } /***--------------------------------------------------------------------------------*WHEREOR*--------------------------------------------------------------------------------**Getthedocumentswherethevalueofa$fieldisinoneormorevalues**@usage=$this->mongo_db->where_or('foo',array('foo','bar','blegh');*/ publicfunctionwhere_or($field="",$values){ $this->where_init($field); $this->wheres[$field]['$or']=$values; return($this); } /***--------------------------------------------------------------------------------*WHEREAND*--------------------------------------------------------------------------------**Getthedocumentswheretheelementsmatchthespecifiedvalues**@usage=$this->mongo_db->where_and(array('foo'=>1,'b'=>'someexample');*/ publicfunctionwhere_and($elements_values=array()){ foreach((array)$elements_valuesas$element=>$val){ $this->wheres[$element]=$val; }return($this); } /***--------------------------------------------------------------------------------*WHEREMOD*--------------------------------------------------------------------------------**Getthedocumentswhere$field%$mod=$result**@usage=$this->mongo_db->where_mod('foo',10,1);*/ publicfunctionwhere_mod($field,$num,$result){ $this->where_init($field); $this->wheres[$field]['$mod']=array($num,$result); return($this); } /***--------------------------------------------------------------------------------*Wheresize*--------------------------------------------------------------------------------**Getthedocumentswherethesizeofafieldisinagiven$sizeint**@usage:$this->mongo_db->where_size('foo',1)->get('foobar');*/ publicfunctionwhere_size($field="",$size=""){ $this->_where_init($field); $this->wheres[$field]['$size']=$size; return($this); } /***--------------------------------------------------------------------------------*LIKEPARAMETERS*--------------------------------------------------------------------------------**Getthedocumentswherethe(string)valueofa$fieldislikeavalue.Thedefaults*allowforacase-insensitivesearch.**@param$flags*Allowsforthetypicalregularexpressionflags:*i=caseinsensitive*m=multiline*x=cancontaincomments*l=locale*s=dotall,"."matcheseverything,includingnewlines*u=matchunicode**@param$enable_start_wildcard*IfsettoanythingotherthanTRUE,astartinglinecharacter"^"willbeprepended*tothesearchvalue,representingonlysearchingforavalueatthestartof*anewline.**@param$enable_end_wildcard*IfsettoanythingotherthanTRUE,anendinglinecharacter"$"willbeappended*tothesearchvalue,representingonlysearchingforavalueattheendof*aline.**@usage=$this->mongo_db->like('foo','bar','im',FALSE,TRUE);*/ publicfunctionlike($field="",$value="",$flags="i",$enable_start_wildcard=TRUE,$enable_end_wildcard=TRUE){ $field=(string)trim($field); $this->where_init($field); $value=(string)trim($value); $value=quotemeta($value); if($enable_start_wildcard!==TRUE){ $value="^".$value; }if($enable_end_wildcard!==TRUE){ $value.="$"; }$regex="/$value/$flags"; $this->wheres[$field]=newMongoRegex($regex); return($this); } publicfunctionwheres($where){ $this->wheres=$where; } /***--------------------------------------------------------------------------------*ORDERBYPARAMETERS*--------------------------------------------------------------------------------**Sortthedocumentsbasedontheparameterspassed.Tosetvaluestodescendingorder,*youmustpassvaluesofeither-1,FALSE,'desc',or'DESC',elsetheywillbe*setto1(ASC).**@usage=$this->mongo_db->where_between('foo',20,30);*/ publicfunctionorder_by($fields=array()){ if(!is_array($fields)||!count($fields))return; foreach($fieldsas$col=>$val){ if($val==-1||$val===FALSE||strtolower($val)=='desc'){ $this->sorts[$col]=-1; }else{ $this->sorts[$col]=1; } }return($this); } /***--------------------------------------------------------------------------------*LIMITDOCUMENTS*--------------------------------------------------------------------------------**Limittheresultsetto$xnumberofdocuments**@usage=$this->mongo_db->limit($x);*/ publicfunctionlimit($x=99999){ if($x!==NULL&&is_numeric($x)&&$x>=1){ $this->limit=(int)$x; }return($this); } /***--------------------------------------------------------------------------------*OFFSETDOCUMENTS*--------------------------------------------------------------------------------**Offsettheresultsettoskip$xnumberofdocuments**@usage=$this->mongo_db->offset($x);*/ publicfunctionoffset($x=0){ if($x!==NULL&&is_numeric($x)&&$x>=1){ $this->offset=(int)$x; }return($this); } /***--------------------------------------------------------------------------------*GET_WHERE*--------------------------------------------------------------------------------**Getthedocumentsbaseduponthepassedparameters**@usage=$this->mongo_db->get_where('foo',array('bar'=>'something'));*/ publicfunctionget_where($collection="",$where=array(),$limit=99999,$orderby=array()){ if(is_array($orderby)||!emptyempty($orderby)){ $order_by=$this->order_by($order_by); } return($this->where($where)->limit($limit)->get($collection)); } publicfunctionselectA($collection="",$limit=99999,$orderby=array()){ if(intval($limit)<1){ $limit=999999; } $order_by=$this->order_by($orderby); $re=$this->limit($limit)->get($collection); $this->clear(); return(array)$re; } publicfunctionlistinfo($collection="",$orderby=array(),$page=1,$pagesize=12){ $page=max(intval($page),1); $offset=$pagesize*($page-1); $pagesizes=$offset+$pagesize; $this->offset($offset); $order_by=$this->order_by($orderby); $re=$this->limit($pagesize)->get($collection); $this->limit(999999); $count=$this->count($collection); $this->pages=pages($count,$page,$pagesize); return(array)$re; } /***--------------------------------------------------------------------------------*GET*--------------------------------------------------------------------------------**Getthedocumentsbaseduponthepassedparameters**@usage=$this->mongo_db->get('foo',array('bar'=>'something'));*/ publicfunctionget($collection=""){ if(emptyempty($collection)){ $this->error("InordertoretreivedocumentsfromMongoDB,acollectionnamemustbepassed",500); }$results=array(); $documents=$this->db->{$collection}->find($this->wheres,$this->selects)->limit((int)$this->limit)->skip((int)$this->offset)->sort($this->sorts); $returns=array(); foreach($documentsas$doc):$returns[]=$doc; endforeach; return($returns); } publicfunctiongetMy($collection=""){ if(emptyempty($collection)){ $this->error("InordertoretreivedocumentsfromMongoDB,acollectionnamemustbepassed",500); }$results=array(); $documents=$this->db->{$collection}->find($this->wheres,$this->selects)->limit((int)$this->limit)->skip((int)$this->offset)->sort($this->sorts); $returns=array(); foreach($documentsas$doc):$returns[]=$doc; endforeach; $this->clear(); return($returns); } /***--------------------------------------------------------------------------------*COUNT*--------------------------------------------------------------------------------**Countthedocumentsbaseduponthepassedparameters**@usage=$this->mongo_db->get('foo');*/ publicfunctioncount($collection=""){ if(emptyempty($collection)){ $this->error("InordertoretreiveacountofdocumentsfromMongoDB,acollectionnamemustbepassed",500); }$count=$this->db->{$collection}->find($this->wheres)->limit((int)$this->limit)->skip((int)$this->offset)->count(); $this->clear(); return($count); } /***--------------------------------------------------------------------------------*INSERT*--------------------------------------------------------------------------------**Insertanewdocumentintothepassedcollection**@usage=$this->mongo_db->insert('foo',$data=array());*/ publicfunctioninsert($collection="",$data=array(),$name='ID'){ if(emptyempty($collection)){ $this->error("NoMongocollectionselectedtoinsertinto",500); }if(count($data)==0||!is_array($data)){ $this->error("NothingtoinsertintoMongocollectionorinsertisnotanarray",500); }try{ /** wxcity_base::load_sys_class('whtysqs','',0); $mongoseq_class=newwhtysqs('creaseidsqs'); $re=$mongoseq_class->query("?name=".$collection."&opt=put&data=1"); **/ $re=put_sqs('list_mongo_creaseidsqs','1'); if(is_numeric($re)){ $re++; $data[$name]=intval($re); }else{ $data[$name]=intval(time()); //die('mongosqserror'); } $this->db->{$collection}->insert($data,array('fsync'=>TRUE)); $this->clear(); return$data[$name]; }catch(MongoCursorException$e){ $this->error("InsertofdataintoMongoDBfailed:{$e->getMessage()}",500); } } publicfunctioninsertWithId($collection="",$data=array()){ if(emptyempty($collection)){ $this->error("NoMongocollectionselectedtoinsertinto",500); }if(count($data)==0||!is_array($data)){ $this->error("NothingtoinsertintoMongocollectionorinsertisnotanarray",500); }try{ $this->db->{$collection}->insert($data,array('fsync'=>TRUE)); $this->clear(); return1; }catch(MongoCursorException$e){ $this->error("InsertofdataintoMongoDBfailed:{$e->getMessage()}",500); } } /***--------------------------------------------------------------------------------*UPDATE*--------------------------------------------------------------------------------**Updateadocumentintothepassedcollection**@usage=$this->mongo_db->update('foo',$data=array());*/ publicfunctionupdate($collection="",$data=array()){ if(emptyempty($collection)){ $this->error("NoMongocollectionselectedtoupdate",500); }if(count($data)==0||!is_array($data)){ $this->error("NothingtoupdateinMongocollectionorupdateisnotanarray",500); }try{ $this->db->{$collection}->update($this->wheres,array('$set'=>$data),array('fsync'=>TRUE,'multiple'=>FALSE)); $this->clear(); return(TRUE); }catch(MongoCursorException$e){ $this->error("UpdateofdataintoMongoDBfailed:{$e->getMessage()}",500); } } /***--------------------------------------------------------------------------------*UPDATE_ALL*--------------------------------------------------------------------------------**Insertanewdocumentintothepassedcollection**@usage=$this->mongo_db->update_all('foo',$data=array());*/ publicfunctionupdate_all($collection="",$data=array()){ if(emptyempty($collection)){ $this->error("NoMongocollectionselectedtoupdate",500); }if(count($data)==0||!is_array($data)){ $this->error("NothingtoupdateinMongocollectionorupdateisnotanarray",500); }try{ $this->db->{$collection}->update($this->wheres,array('$set'=>$data),array('fsync'=>TRUE,'multiple'=>TRUE)); return(TRUE); }catch(MongoCursorException$e){ $this->error("UpdateofdataintoMongoDBfailed:{$e->getMessage()}",500); } } /***--------------------------------------------------------------------------------*DELETE*--------------------------------------------------------------------------------**deletedocumentfromthepassedcollectionbaseduponcertaincriteria**@usage=$this->mongo_db->delete('foo',$data=array());*/ publicfunctiondelete($collection=""){ if(emptyempty($collection)){ $this->error("NoMongocollectionselectedtodeletefrom",500); }try{ $this->db->{$collection}->remove($this->wheres,array('fsync'=>TRUE,'justOne'=>TRUE)); $this->clear(); return(TRUE); }catch(MongoCursorException$e){ $this->error("DeleteofdataintoMongoDBfailed:{$e->getMessage()}",500); } } /***--------------------------------------------------------------------------------*DELETE_ALL*--------------------------------------------------------------------------------**Deletealldocumentsfromthepassedcollectionbaseduponcertaincriteria**@usage=$this->mongo_db->delete_all('foo',$data=array());*/ publicfunctiondelete_all($collection=""){ if(emptyempty($collection)){ $this->error("NoMongocollectionselectedtodeletefrom",500); }try{ $this->db->{$collection}->remove($this->wheres,array('fsync'=>TRUE,'justOne'=>FALSE)); return(TRUE); }catch(MongoCursorException$e){ $this->error("DeleteofdataintoMongoDBfailed:{$e->getMessage()}",500); } } /***--------------------------------------------------------------------------------*ADD_INDEX*--------------------------------------------------------------------------------**Ensureanindexofthekeysinacollectionwithoptionalparameters.Tosetvaluestodescendingorder,*youmustpassvaluesofeither-1,FALSE,'desc',or'DESC',elsetheywillbe*setto1(ASC).**@usage=$this->mongo_db->add_index($collection,array('first_name'=>'ASC','last_name'=>-1),array('unique'=>TRUE));*/ publicfunctionadd_index($collection="",$keys=array(),$options=array()){ if(emptyempty($collection)){ $this->error("NoMongocollectionspecifiedtoaddindexto",500); }if(emptyempty($keys)||!is_array($keys)){ $this->error("IndexcouldnotbecreatedtoMongoDBCollectionbecausenokeyswerespecified",500); }foreach($keysas$col=>$val){ if($val==-1||$val===FALSE||strtolower($val)=='desc'){ $keys[$col]=-1; }else{ $keys[$col]=1; } }if($this->db->{$collection}->ensureIndex($keys,$options)==TRUE){ $this->clear(); return($this); }else{ $this->error("AnerroroccuredwhentryingtoaddanindextoMongoDBCollection",500); } } /***--------------------------------------------------------------------------------*REMOVE_INDEX*--------------------------------------------------------------------------------**Removeanindexofthekeysinacollection.Tosetvaluestodescendingorder,*youmustpassvaluesofeither-1,FALSE,'desc',or'DESC',elsetheywillbe*setto1(ASC).**@usage=$this->mongo_db->remove_index($collection,array('first_name'=>'ASC','last_name'=>-1));*/ publicfunctionremove_index($collection="",$keys=array()){ if(emptyempty($collection)){ $this->error("NoMongocollectionspecifiedtoremoveindexfrom",500); }if(emptyempty($keys)||!is_array($keys)){ $this->error("IndexcouldnotberemovedfromMongoDBCollectionbecausenokeyswerespecified",500); }if($this->db->{$collection}->deleteIndex($keys,$options)==TRUE){ $this->clear(); return($this); }else{ $this->error("AnerroroccuredwhentryingtoremoveanindexfromMongoDBCollection",500); } } /***--------------------------------------------------------------------------------*REMOVE_ALL_INDEXES*--------------------------------------------------------------------------------**Removeallindexesfromacollection.**@usage=$this->mongo_db->remove_all_index($collection);*/ publicfunctionremove_all_indexes($collection=""){ if(emptyempty($collection)){ $this->error("NoMongocollectionspecifiedtoremoveallindexesfrom",500); }$this->db->{$collection}->deleteIndexes(); $this->clear(); return($this); } /***--------------------------------------------------------------------------------*LIST_INDEXES*--------------------------------------------------------------------------------**Listsallindexesinacollection.**@usage=$this->mongo_db->list_indexes($collection);*/ publicfunctionlist_indexes($collection=""){ if(emptyempty($collection)){ $this->error("NoMongocollectionspecifiedtoremoveallindexesfrom",500); }return($this->db->{$collection}->getIndexInfo()); } /***--------------------------------------------------------------------------------*DROPCOLLECTION*--------------------------------------------------------------------------------**Removesthespecifiedcollectionfromthedatabase.Becarefulbecausethis*canhavesomeverylargeissuesinproduction!*/ publicfunctiondrop_collection($collection=""){ if(emptyempty($collection)){ $this->error("NoMongocollectionspecifiedtodropfromdatabase",500); }$this->db->{$collection}->drop(); returnTRUE; } /***--------------------------------------------------------------------------------*CLEAR*--------------------------------------------------------------------------------**Resetstheclassvariablestodefaultsettings*/ privatefunctionclear(){ $this->selects=array(); $this->wheres=array(); $this->limit=NULL; $this->offset=NULL; $this->sorts=array(); } /***--------------------------------------------------------------------------------*WHEREINITIALIZER*--------------------------------------------------------------------------------**Preparesparametersforinsertionin$wheresarray().*/ privatefunctionwhere_init($param){ if(!isset($this->wheres[$param])){ $this->wheres[$param]=array(); } } publicfunctionerror($str,$t){ echo$str; exit; } } ?>
使用范例:
$table_name=trim(strtolower($this->table_name)); $this->mongo_db->where($where); $order=!emptyempty($order)?array('AID'=>'DESC'):array('AID'=>'ASC');//升序降序 $infos=$this->mongo_db->listinfo($table_name,$order,$page,$pagesize);
这篇文章就到这结束了,大家可以多学习一下