php操作MongoDB类实例
本文实例讲述了php操作MongoDB类的方法。分享给大家供大家参考。具体如下:
1.MyMongo.php文件:
<?php
/**
*仿写CI的MongoDB
*@authorsparkHuang2011-11-03
*
*/
classMyMongo{
private$mongo_config="mongo_config.php";
private$connection;
private$db;
private$mongo_connect_string;
private$host;
private$port;
private$user;
private$pass;
private$dbname;
private$persist;
private$persist_key;
private$selects=array();
private$wheres=array();
private$sorts=array();
private$limit=999999;
private$offset=0;
publicfunction__construct(){
if(!class_exists('Mongo')){
$this->log_error("TheMongoDBPECLextentiosnhasnotbeeninstalledorenabled.");
exit;
}
$this->connection_string();
$this->connect();
}
/**
*更改数据库
*
*/
publicfunctionswitch_db($database=''){
if(empty($database)){
$this->log_error("ToswitchMongoDBdatabases,anewdatabasenamemustbespecified");
exit;
}
$this->dbname=$database;
try{
$this->db=$this->connection->{$this->dbname};
returntrue;
}catch(Exception$e){
$this->log_error("UnabletoswitchMongoDatabases:{$e->getMessage()}");
exit;
}
}
/**
*设置select字段
*
*/
publicfunctionselect($includs=array(),$excludes=array()){
if(!is_array($includs)){
$includs=(array)$includs;
}
if(!is_array($excludes)){
$excludes=(array)$excludes;
}
if(!empty($includs)){
foreach($includsas$col){
$this->selects[$col]=1;
}
}else{
foreach($excludesas$col){
$this->selects[$col]=0;
}
}
return($this);
}
/**
*where条件查询判断
*
*@usage=$this->mongo_db->where(array('foo'=>'bar'))->get('foobar');
*
*/
publicfunctionwhere($wheres=array()){
if(!is_array($wheres)){
$wheres=(array)$wheres;
}
if(!empty($wheres)){
foreach($wheresas$wh=>$val){
$this->wheres[$wh]=$val;
}
}
return($this);
}
/**
*where...in..条件查询判断
*
*@usage=$this->mongo_db->where_in('foo',array('bar','zoo'))->get('foobar');
*
*/
publicfunctionwhere_in($field='',$in=array()){
$this->where_init($field);
$this->wheres[$field]['$in']=$in;
return($this);
}
/**
*where...notin..条件查询判断
*
*@usage=$this->mongo_db->where_not_in('foo',array('bar','zoo'))->get('foobar');
*
*/
publicfunctionwhere_not_in($field='',$in=array()){
$this->where_init($field);
$this->wheres[$field]['$nin']=$in;
return($this);
}
/**
*where...$field>$x..条件查询判断
*
*@usage=$this->mongo_db->where_gt('foo',20)->get('foobar');
*
*/
publicfunctionwhere_gt($field='',$x){
$this->where_init($field);
$this->wheres[$field]['$gt']=$x;
return($this);
}
/**
*where...$field>=$x..条件查询判断
*
*@usage=$this->mongo_db->where_gte('foo',20)->get('foobar');
*
*/
publicfunctionwhere_gte($field='',$x){
$this->where_init($field);
$this->wheres[$field]['$gte']=$x;
return($this);
}
/**
*where...$field<$x..条件查询判断
*
*@usage=$this->mongo_db->where_lt('foo',20)->get('foobar');
*
*/
publicfunctionwhere_lt($field='',$x){
$this->where_init($field);
$this->wheres[$field]['$lt']=$x;
return($this);
}
/**
*where...$field<=$x..条件查询判断
*
*@usage=$this->mongo_db->where_lte('foo',20)->get('foobar');
*
*/
publicfunctionwhere_lte($field='',$x){
$this->where_init($field);
$this->wheres[$field]['$lte']=$x;
return($this);
}
/**
*where...$field>=$xAND$field<=$y..条件查询判断
*
*@usage=$this->mongo_db->where_between('foo',20,30)->get('foobar');
*
*/
publicfunctionwhere_between($field='',$x,$y){
$this->where_init($field);
$this->wheres[$field]['$gte']=$x;
$this->wheres[$field]['$lte']=$y;
return($this);
}
/**
*where...$field>$xAND$field<$y..条件查询判断
*
*@usage=$this->mongo_db->where_between_ne('foo',20,30)->get('foobar');
*
*/
publicfunctionwhere_between_ne($field='',$x,$y){
$this->where_init($field);
$this->wheres[$field]['$gt']=$x;
$this->wheres[$field]['$lt']=$y;
return($this);
}
/**
*where...$field<>$x..条件查询判断
*
*@usage=$this->mongo_db->where_ne('foo',20)->get('foobar');
*
*/
publicfunctionwhere_ne($field='',$x){
$this->where_init($field);
$this->wheres[$field]['$ne']=$x;
return($this);
}
/**
*where...or..条件查询判断
*
*@usage=$this->mongo_db->where_or('foo',array('foo','bar'))->get('foobar');
*
*/
publicfunctionwhere_or($field='',$values){
$this->where_init($field);
$this->wheres[$field]['$or']=$values;
return($this);
}
/**
*where...and..条件查询判断
*
*@usage=$this->mongo_db->where_and(array('foo'=>1,'b'=>'someexample');
*/
publicfunctionwhere_and($elements_values=array()){
foreach($elements_valuesas$element=>$val){
$this->wheres[$element]=$val;
}
return($this);
}
/**
*where$field%$num=$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);
}
/**
*like条件查询(PHP中定义MongoRegex类实现)
*
*@usage:$this->mongo_db->like('foo','bar','im',false,false)->get();
*/
publicfunctionlike($field="",$value="",$flags="i",$enable_start_wildcard=true,$enable_end_wildcard=true){
$field=(string)$field;
$this->where_init($field);
$value=(string)$value;
$value=quotmeta($value);
if(true!==$enable_start_wildcard){
$value="^".$value;
}
if(true!==$enable_end_wildcard){
$value.="$";
}
$regex="/$value/$flags";
$this->wheres[$field]=newMongoRegex($regex);
return($this);
}
/**
*order排序(1=>ASC,-1=>DESC)
*
*@usage:$this->mongo_db->get_where('foo',array('name'=>'tom'))->order_by(array("age"=>1));
*/
publicfunctionorder_by($fields=array()){
foreach($fieldsas$col=>$val){
if($val==-1||$val==false||strtolower($val)=="desc"){
$this->sorts[$col]=-1;
}else{
$this->sorts[$col]=1;
}
}
return($this);
}
/**
*limit
*
*@usage:$this->mongo_db->get_where('foo',array('name'=>'tom'))->limit(10);
*/
publicfunctionlimit($x=999999){
if($x!==NULL&&is_numeric($x)&&$x>=1){
$this->limit=(int)$x;
}
return($this);
}
/**
*offset
*
*@usage:$this->mongo_db->get_where('foo',array('name'=>'tom'))->offset(10);
*/
publicfunctionoffset($x=0){
if($x!==NULL&&is_numeric($x)&&$x>=1){
$this->offset=(int)$x;
}
return($this);
}
/**
*get_where
*
*@usage:$this->mongo_db->get_where('foo',array('bar'=>'something'));
*/
publicfunctionget_where($collection="",$where=array(),$limit=999999){
return($this->where($where)->limit($limit)->get($collection));
}
/**
*get
*
*@usage:$this->mongo_db->where(array('name'=>'tom'))->get('foo');
*/
publicfunctionget($collection){
if(empty($collection)){
$this->log_error("InordertoretreivedocumentsfromMongoDB,acollectionnamemustbepassed");
exit;
}
$results=array();
$results=$this->db->{$collection}->find($this->wheres,$this->selects)->limit((int)$this->limit)->skip((int)$this->offset)->sort($this->sorts);
$returns=array();
foreach($resultsas$result){
$returns[]=$result;
}
$this->clear();
return($returns);
}
/**
*count
*
*@usage:$this->db->get_where('foo',array('name'=>'tom'))->count('foo');
*/
publicfunctioncount($collection){
if(empty($collection)){
$this->log_error("InordertoretreivedocumentsfromMongoDB,acollectionnamemustbepassed");
exit;
}
$count=$this->db->{$collection}->find($this->wheres)->limit((int)$this->limit)->skip((int)$this->offset)->count();
$this->clear();
return($count);
}
/**
*insert
*
*@usage:$this->mongo_db->insert('foo',array('name'=>'tom'));
*/
publicfunctioninsert($collection="",$data=array()){
if(empty($collection)){
$this->log_error("NoMongocollectionselectedtodeletefrom");
exit;
}
if(count($data)==0||!is_array($data)){
$this->log_error("NothingtoinsertintoMongocollectionorinsertisnotanarray");
exit;
}
try{
$this->db->{$collection}->insert($data,array('fsync'=>true));
if(isset($data['_id'])){
return($data['_id']);
}else{
return(false);
}
}catch(MongoCursorException$e){
$this->log_error("InsertofdataintoMongoDBfailed:{$e->getMessage()}");
exit;
}
}
/**
*update:利用MongoDB的$set实现
*
*@usage:$this->mongo_db->where(array('name'=>'tom'))->update('foo',array('age'=>24))
*/
publicfunctionupdate($collection="",$data=array()){
if(empty($collection)){
$this->log_error("NoMongocollectionselectedtodeletefrom");
exit;
}
if(count($data)==0||!is_array($data)){
$this->log_error("NothingtoupdateinMongocollectionorupdateisnotanarray");
exit;
}
try{
$this->db->{$collection}->update($this->wheres,array('$set'=>$data),array('fsync'=>true,'multiple'=>false));//注意:multiple为false
return(true);
}catch(MongoCursorException$e){
$this->log_error("UpdateofdataintoMongoDBfailed:{$e->getMessage()}");
exit;
}
}
/**
*update_all:利用MongoDB的$set实现
*
*@usage:$this->mongo_db->where(array('name'=>'tom'))->update_all('foo',array('age'=>24));
*/
publicfunctionupdate_all($collection="",$data=array()){
if(empty($collection)){
$this->log_error("NoMongocollectionselectedtodeletefrom");
exit;
}
if(count($data)==0||!is_array($data)){
$this->log_error("NothingtoupdateinMongocollectionorupdateisnotanarray");
exit;
}
try{
$this->db->{$collection}->update($this->wheres,array('$set'=>$data),array('fsync'=>true,'multiple'=>true));//注意:multiple为true
return(true);
}catch(MongoCursorException$e){
$this->log_error("UpdateofdataintoMongoDBfailed:{$e->getMessage()}");
exit;
}
}
/**
*delete
*
*@usage:$this->mongo_db->where(array('name'=>'tom'))->delete('foo');
*/
publicfunctiondelete($collection=""){
if(empty($collection)){
$this->log_error("NoMongocollectionselectedtodeletefrom");
exit;
}
try{
$this->db->{$collection}->remove($this->wheres,array('fsync'=>true,'justOne'=>true));//注意justOne为true;
}catch(MongoCursorException$e){
$this->log_error("DeleteofdataintoMongoDBfailed:{$e->getMessage()}");
exit;
}
}
/**
*delete_all
*
*@usage:$this->mongo_db->where(array('name'=>'tom'))->delete_all('foo');
*/
publicfunctiondelete_all($collection=""){
if(empty($collection)){
$this->log_error("NoMongocollectionselectedtodeletefrom");
exit;
}
try{
$this->db->{$collection}->remove($this->wheres,array('fsync'=>true,'justOne'=>false));//注意justOne为false;
}catch(MongoCursorException$e){
$this->log_error("DeleteofdataintoMongoDBfailed:{$e->getMessage()}");
exit;
}
}
/**
*add_index
*
*@usage:$this->mongo_db->add_index('foo',array('first_name'=>'ASC','last_name'=>-1),array('unique'=>true)));
*/
publicfunctionadd_index($collection,$keys=array(),$options=array()){
if(empty($collection)){
$this->log_error("NoMongocollectionspecifiedtoaddindexto");
exit;
}
if(empty($keys)||!is_array($keys)){
$this->log_error("IndexcouldnotbecreatedtoMongoDBCollectionbecausenokeyswerespecified");
exit;
}
foreach($keysas$col=>$val){
if($val==-1||$val==false||strtolower($val)=='desc'){
$keys[$col]=-1;
}else{
$keys[$col]=1;
}
}
//在此没有对$options数组的有效性进行验证
if(true==$this->db->{$collection}->ensureIndex($keys,$options)){
$this->clear();
return($this);
}else{
$this->log_error("AnerroroccuredwhentryingtoaddanindextoMongoDBCollection");
exit;
}
}
/**
*remove_index
*
*@usage:$this->mongo_db->remove_index('foo',array('first_name'=>'ASC','last_name'=>-1))
*/
publicfunctionremove_index($collection="",$keys=array()){
if(empty($collection)){
$this->log_error("NoMongocollectionspecifiedtoaddindexto");
exit;
}
if(empty($keys)||!is_array($keys)){
$this->log_error("IndexcouldnotbecreatedtoMongoDBCollectionbecausenokeyswerespecified");
exit;
}
if($this->db->{$collection}->deleteIndex($keys)){
$this->clear();
return($this);
}else{
$this->log_error("AnerroroccuredwhentryingtoaddanindextoMongoDBCollection");
exit;
}
}
/**
*remove_all_index
*
*@usage:$this->mongo_db->remove_all_index('foo',array('first_name'=>'ASC','last_name'=>-1))
*/
publicfunctionremove_all_index($collection="",$keys=array()){
if(empty($collection)){
$this->log_error("NoMongocollectionspecifiedtoaddindexto");
exit;
}
if(empty($keys)||!is_array($keys)){
$this->log_error("IndexcouldnotbecreatedtoMongoDBCollectionbecausenokeyswerespecified");
exit;
}
if($this->db->{$collection}->deleteIndexes($keys)){
$this->clear();
return($this);
}else{
$this->log_error("AnerroroccuredwhentryingtoaddanindextoMongoDBCollection");
exit;
}
}
/**
*list_indexes
*
*@usage:$this->mongo_db->list_indexes('foo');
*/
publicfunctionlist_indexes($collection=""){
if(empty($collection)){
$this->log_error("NoMongocollectionspecifiedtoaddindexto");
exit;
}
return($this->db->{$collection}->getIndexInfo());
}
/**
*drop_collection
*
*@usage:$this->mongo_db->drop_collection('foo');
*/
publicfunctiondrop_collection($collection=""){
if(empty($collection)){
$this->log_error("NoMongocollectionspecifiedtoaddindexto");
exit;
}
$this->db->{$collection}->drop();
return(true);
}
/**
*生成连接MongoDB参数字符串
*
*/
privatefunctionconnection_string(){
include_once($this->mongo_config);
$this->host=trim($config['host']);
$this->port=trim($config['port']);
$this->user=trim($config['user']);
$this->pass=trim($config['pass']);
$this->dbname=trim($config['dbname']);
$this->persist=trim($config['persist']);
$this->persist_key=trim($config['persist_key']);
$connection_string="mongodb://";
if(empty($this->host)){
$this->log_error("TheHostmustbesettoconnecttoMongoDB");
exit;
}
if(empty($this->dbname)){
$this->log_error("TheDatabasemustbesettoconnecttoMongoDB");
exit;
}
if(!empty($this->user)&&!empty($this->pass)){
$connection_string.="{$this->user}:{$this->pass}@";
}
if(isset($this->port)&&!empty($this->port)){
$connection_string.="{$this->host}:{$this->port}";
}else{
$connection_string.="{$this->host}";
}
$this->connection_string=trim($connection_string);
}
/**
*连接MongoDB获取数据库操作句柄
*
*/
privatefunctionconnect(){
$options=array();
if(true===$this->persist){
$options['persist']=isset($this->persist_key)&&!empty($this->persist_key)?$this->persist_key:"ci_mongo_persist";
}
try{
$this->connection=newMongo($this->connection_string,$options);
$this->db=$this->connection->{$this->dbname};
return($this);
}catch(MongoConnectionException$e){
$this->log_error("UnabletoconnecttoMongoDB:{$e->getMessage()}");
}
}
/**
*初始化清理部分成员变量
*
*/
privatefunctionclear(){
$this->selects=array();
$this->wheres=array();
$this->limit=NULL;
$this->offset=NULL;
$this->sorts=array();
}
/**
*依据字段名初始化处理$wheres数组
*
*/
privatefunctionwhere_init($param){
if(!isset($this->wheres[$param])){
$this->wheres[$param]=array();
}
}
/**
*错误记录
*
*/
privatefunctionlog_error($msg){
$msg="[Date:".date("Y-m-iH:i:s")."]".$msg;
@file_put_contents("./error.log",print_r($msg."\n",true),FILE_APPEND);
}
}
/*EndofMyMongo.php*/
2.mongo_config.php配置文件:
<?php $config["host"]="localhost"; $config["user"]=""; $config["pass"]=""; $config["port"]=27017; $config["dbname"]="test"; $config['persist']=TRUE; $config['persist_key']='ci_mongo_persist'; /*Endofmongo_config.php*/
3.MyMongoDemo.php文件:
<?php
include_once("MyMongo.php");
$conn=newMyMongo();
//删除所有记录
$conn->delete_all("blog");
//插入第一条记录
$value=array("name"=>"小明","age"=>25,"addr"=>array("country"=>"中国","province"=>"广西","city"=>"桂林"));
$conn->insert("blog",$value);
var_dump($conn->select(array("name","age"))->get("blog"));
var_dump($conn->get("blog"));
/*EndofMyMongoDemo.php*/
希望本文所述对大家的php程序设计有所帮助。