类文件:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); if(!function_exists('show_error')){ function show_error($msg,$code){ echo $msg; exit; } } if(function_exists('get_instance')){ $CI =& get_instance(); $CI->config->load("cimongo"); $GLOBALS['host'] = trim($CI->config->item('host')); $GLOBALS['port'] = trim($CI->config->item('port')); $GLOBALS['user'] = trim($CI->config->item('user')); $GLOBALS['pass'] = trim($CI->config->item('pass')); $GLOBALS['dbname'] = trim($CI->config->item('db')); $GLOBALS['query_safety'] = $CI->config->item('query_safety'); $GLOBALS['dbhostflag'] = (bool)$CI->config->item('db_flag'); $GLOBALS['mongo_return'] = (bool)$CI->config->item('mongo_return'); }else{ $GLOBALS['host'] = trim("127.0.0.1"); $GLOBALS['port'] = trim("27017"); $GLOBALS['user'] = trim("user1"); $GLOBALS['pass'] = trim("123456"); $GLOBALS['dbname'] = trim("codeigniter"); $GLOBALS['query_safety'] = true; $GLOBALS['dbhostflag'] = true; $GLOBALS['mongo_return'] = ''; } class Cimongo extends Cimongo_extras { private $_inserted_id = FALSE; public $debug = FALSE; public function __construct() { parent::__construct(); } public function close() { } public function get($collection = "", $limit = FALSE, $offset = FALSE) { if (empty($collection)) { //FIXME theow exception instead show error show_error("In order to retreive documents from MongoDB, a collection name must be passed", 500); } $cursor = $this->db->selectCollection($collection)->find($this->wheres, $this->selects); $cimongo_cursor = new Cimongo_cursor($cursor); $this->limit = ($limit !== FALSE && is_numeric($limit)) ? $limit : $this->limit; if ($this->limit !== FALSE) { $cimongo_cursor->limit($this->limit); } $this->offset = ($offset !== FALSE && is_numeric($offset)) ? $offset : $this->offset; if ($this->offset !== FALSE) { $cimongo_cursor->skip($this->offset); } if (!empty($this->sorts) && count($this->sorts) > 0) { $cimongo_cursor->sort($this->sorts); } $this->_clear(); return $cimongo_cursor; } public function get_where($collection = "", $where = array(), $limit = FALSE, $offset = FALSE) { return $this->where($where)->get($collection, $limit, $offset); } public function select($includes = array()) { if (!is_array($includes)) { $includes = array(); } if (!empty($includes)) { foreach ($includes as $col) { $this->selects[$col] = TRUE; } } return $this; } public function where($wheres = array(), $values = '') { if (is_array($wheres)) { foreach ($wheres as $where => $value) { $this->_where_init($where); $this->wheres[$where] = $value; } }else{ $this->where(array($wheres=>$values)); } return $this; } public function or_where($wheres = array(),$value='') { if(is_array($wheres)) { $this->_where_init('$or'); if (is_array($wheres) && count($wheres) > 0) { foreach ($wheres as $wh => $val) { $this->wheres['$or'][] = array($wh => $val); } } }else{ $this->or_where(array($wheres=>$value)); } return $this; } public function where_in($field = "", $in = array()) { $this->_where_init($field); $this->wheres[$field]['$in'] = $in; return $this; } public function where_not_in($field = "", $in = array()) { $this->_where_init($field); $this->wheres[$field]['$nin'] = $in; return $this; } public function like($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] = new MongoRegex($regex); return $this; } public function or_like($field, $like = array(),$flags = "i") { $this->_where_init('$or'); if (is_array($like) && count($like) > 0) { foreach ($like as $admitted) { $this->wheres['$or'][] = array($field => new MongoRegex("/$admitted/$flags")); } } else { $this->wheres['$or'][] = array($field => new MongoRegex("/$like/$flags")); } return $this; } public function not_like($field, $like = array()) { $this->_where_init($field); if (is_array($like) && count($like) > 0) { foreach ($like as $admitted) { $this->wheres[$field]['$nin'][] = new MongoRegex("/$admitted/"); } } return $this; } public function order_by($fields = array(),$value='') { if(is_array($fields)) { foreach ($fields as $field => $val) { if ($val === -1 || $val === FALSE || strtolower($val) === 'desc') { $this->sorts[$field] = -1; } if ($val === 1 || $val === TRUE || strtolower($val) === 'asc') { $this->sorts[$field] = 1; } } }else{ if(strtolower($value) === 'asc'){ $this->sorts[$fields] = 1; }else{ $this->sorts[$fields] = -1; } } return $this; } public function count_all($collection = "") { if (empty($collection)) { show_error("In order to retreive a count of documents from MongoDB, a collection name must be passed", 500); } $cursor = $this->db->selectCollection($collection)->find(); $cimongo_cursor = new Cimongo_cursor($cursor); $count = $cimongo_cursor->count(TRUE); $this->_clear(); return $count; } public function count_all_results($collection = "") { if (empty($collection)) { show_error("In order to retreive a count of documents from MongoDB, a collection name must be passed", 500); } $cursor = $this->db->selectCollection($collection)->find($this->wheres); $cimongo_cursor = new Cimongo_cursor($cursor); if ($this->limit !== FALSE) { $cimongo_cursor->limit($this->limit); } if ($this->offset !== FALSE) { $cimongo_cursor->skip($this->offset); } $this->_clear(); return $cimongo_cursor->count(TRUE); } public function insert($collection = "", $insert = array()) { if (empty($collection)) { show_error("No Mongo collection selected to insert into", 500); } if (count($insert) == 0) { show_error("Nothing to insert into Mongo collection or insert is not an array", 500); } $this->_inserted_id = FALSE; try { $query = $this->db->selectCollection($collection)->insert($insert, array("w" => $this->query_safety)); if (isset($insert['_id'])) { $this->_inserted_id = $insert['_id']; return TRUE; } else { return FALSE; } } catch (MongoException $e) { show_error("Insert of data into MongoDB failed: {$e->getMessage()}", 500); } catch (MongoCursorException $e) { show_error("Insert of data into MongoDB failed: {$e->getMessage()}", 500); } } public function insert_batch($collection = "", $insert = array()) { if (empty($collection)) { show_error("No Mongo collection selected to insert into", 500); } if (count($insert) == 0) { show_error("Nothing to insert into Mongo collection or insert is not an array", 500); } try { $query = $this->db->selectCollection($collection)->batchInsert($insert, array("w" => $this->query_safety)); if (is_array($query)) { return $query["err"] === NULL; } else { return $query; } } catch (MongoException $e) { show_error("Insert of data into MongoDB failed: {$e->getMessage()}", 500); } catch (MongoCursorException $e) { show_error("Insert of data into MongoDB failed: {$e->getMessage()}", 500); } catch (MongoCursorTimeoutException $e) { show_error("Insert of data into MongoDB failed: {$e->getMessage()}", 500); } } public function set($fields = array()) { if (is_array($fields)) { $this->_update_init('$set'); foreach ($fields as $field => $value) { $this->updates['$set'][$field] = $value; } } return $this; } public function update($collection = "", $data = array(), $options = array('multiple' => TRUE)) { if (empty($collection)) { show_error("No Mongo collection selected to update", 500); } if (is_array($data) && count($data) > 0) { $this->_update_init('$set'); $this->updates['$set'] += $data; } if (count($this->updates) == 0) { show_error("Nothing to update in Mongo collection or update is not an array", 500); } try { $options = array_merge(array("w" => $this->query_safety, 'multiple' => FALSE), $options); $this->db->selectCollection($collection)->update($this->wheres, $this->updates, $options); $this->_clear(); return TRUE; } catch (MongoCursorException $e) { show_error("Update of data into MongoDB failed: {$e->getMessage()}", 500); } catch (MongoCursorException $e) { show_error("Update of data into MongoDB failed: {$e->getMessage()}", 500); } catch (MongoCursorTimeoutException $e) { show_error("Update of data into MongoDB failed: {$e->getMessage()}", 500); } } public function update_batch($collection = "", $data = array()) { return $this->update($collection, $data, array('multiple' => TRUE)); } public function delete($collection = "", $options = array('justOne' => FALSE)) { if (empty($collection)) { show_error("No Mongo collection selected to delete from", 500); } try { $options = array_merge(array("w" => $this->query_safety), $options); $this->db->selectCollection($collection)->remove($this->wheres, $options); $this->_clear(); return TRUE; } catch (MongoCursorException $e) { show_error("Delete of data into MongoDB failed: {$e->getMessage()}", 500); } catch (MongoCursorTimeoutException $e) { show_error("Delete of data into MongoDB failed: {$e->getMessage()}", 500); } } public function delete_batch($collection = "", $options = array()) { return $this->delete($collection, array('justOne' => FALSE)); } public function limit($limit = FALSE,$offset=0) { if ($limit && is_numeric($limit)) { $this->limit = $limit; } if ($offset && is_numeric($offset)) { $this->offset = $offset; } return $this; } public function insert_id() { return $this->_inserted_id; } } class Cimongo_extras extends Cimongo_base{ public function __construct(){ parent::__construct(); } public function command($query = array()){ try{ $run = $this->db->command($query); return $run; }catch (MongoCursorException $e){ show_error("MongoDB command failed to execute: {$e->getMessage()}", 500); } } public function aggregate($collection = "", $opt) { if (empty($collection)) { show_error("No Mongo collection selected to insert into", 500); } try{ $c = $this->db->selectCollection($collection); return $c->aggregate($opt); } catch (MongoException $e) { show_error("MongoDB failed: {$e->getMessage()}", 500); } } public function ensure_index($collection = "", $keys = array(), $options = array()){ if(empty($collection)){ show_error("No Mongo collection specified to add index to", 500); } if(empty($keys) || !is_array($keys)){ show_error("Index could not be created to MongoDB Collection because no keys were specified", 500); } foreach ($keys as $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{ show_error("An error occured when trying to add an index to MongoDB Collection", 500); } } public function remove_index($collection = "", $keys = array()){ if (empty($collection)) { show_error("No Mongo collection specified to remove index from", 500); } if (empty($keys) || !is_array($keys)) { show_error("Index could not be removed from MongoDB Collection because no keys were specified", 500); } if ($this->db->{$collection}->deleteIndex($keys, $options) == TRUE){ $this->_clear(); return $this; } else{ show_error("An error occured when trying to remove an index from MongoDB Collection", 500); } } public function remove_all_indexes($collection = ""){ if (empty($collection)){ show_error("No Mongo collection specified to remove all indexes from", 500); } $this->db->{$collection}->deleteIndexes(); $this->_clear(); return $this; } public function list_indexes($collection = ""){ if (empty($collection)){ show_error("No Mongo collection specified to remove all indexes from", 500); } return $this->db->{$collection}->getIndexInfo(); } public function get_dbref($obj){ if (empty($obj) OR !isset($obj)){ show_error('To use MongoDBRef::get() ala get_dbref() you must pass a valid reference object', 500); } if ($GLOBALS['mongo_return'] == 'object'){ return (object) MongoDBRef::get($this->db, $obj); } else{ return (array) MongoDBRef::get($this->db, $obj); } } public function create_dbref($collection = "", $id = "", $database = FALSE ){ if (empty($collection)) { show_error("In order to retreive documents from MongoDB, a collection name must be passed", 500); } if (empty($id) OR !isset($id)) { show_error('To use MongoDBRef::create() ala create_dbref() you must pass a valid id field of the object which to link', 500); } $db = $database ? $database : $this->db; if ($GLOBALS['mongo_return'] == 'object'){ return (object) MongoDBRef::create($collection, $id, $db); }else{ return (array) MongoDBRef::get($this->db, $obj); } } public function where_gt($field = "", $x){ $this->_where_init($field); $this->wheres[$field]['$gt'] = $x; return $this; } public function where_gte($field = "", $x){ $this->_where_init($field); $this->wheres[$field]['$gte'] = $x; return $this; } public function where_lt($field = "", $x){ $this->_where_init($field); $this->wheres[$field]['$lt'] = $x; return $this; } public function where_lte($field = "", $x){ $this->_where_init($field); $this->wheres[$field]['$lte'] = $x; return $this; } public function where_between($field = "", $x, $y){ $this->_where_init($field); $this->wheres[$field]['$gte'] = $x; $this->wheres[$field]['$lte'] = $y; return $this; } public function where_between_ne($field = "", $x, $y){ $this->_where_init($field); $this->wheres[$field]['$gt'] = $x; $this->wheres[$field]['$lt'] = $y; return $this; } public function where_ne($field = '', $x){ $this->_where_init($field); $this->wheres[$field]['$ne'] = $x; return $this; } function where_near($field = '', $co = array()){ $this->__where_init($field); $this->where[$what]['$near'] = $co; return $this; } public function inc($fields = array(), $value = 0){ $this->_update_init('$inc'); if (is_string($fields)){ $this->updates['$inc'][$fields] = $value; }elseif(is_array($fields)){ foreach ($fields as $field => $value){ $this->updates['$inc'][$field] = $value; } } return $this; } public function dec($fields = array(), $value = 0){ $this->_update_init('$dec'); if (is_string($fields)){ $this->updates['$dec'][$fields] = $value; }elseif (is_array($fields)){ foreach ($fields as $field => $value){ $this->updates['$dec'][$field] = $value; } } return $this; } public function unset_field($fields){ $this->_update_init('$unset'); if (is_string($fields)){ $this->updates['$unset'][$fields] = 1; }elseif (is_array($fields)){ foreach ($fields as $field) { $this->updates['$unset'][$field] = 1; } } return $this; } public function addtoset($field, $values){ $this->_update_init('$addToSet'); if (is_string($values)){ $this->updates['$addToSet'][$field] = $values; }elseif (is_array($values)){ $this->updates['$addToSet'][$field] = array('$each' => $values); } return $this; } public function push($fields, $value = array()){ $this->_update_init('$push'); if (is_string($fields)){ $this->updates['$push'][$fields] = $value; }elseif (is_array($fields)){ foreach ($fields as $field => $value){ $this->updates['$push'][$field] = $value; } } return $this; } public function push_all($fields, $value = array()) { $this->_update_init('$pushAll'); if (is_string($fields)){ $this->updates['$pushAll'][$fields] = $value; }elseif (is_array($fields)){ foreach ($fields as $field => $value){ $this->updates['$pushAll'][$field] = $value; } } return $this; } public function pop($field){ $this->_update_init('$pop'); if (is_string($field)){ $this->updates['$pop'][$field] = -1; } elseif (is_array($field)){ foreach ($field as $pop_field){ $this->updates['$pop'][$pop_field] = -1; } } return $this; } public function pull($field = "", $value = array()){ $this->_update_init('$pull'); $this->updates['$pull'] = array($field => $value); return $this; } public function pull_all($field = "", $value = array()){ $this->_update_init('$pullAll'); $this->updates['$pullAll'] = array($field => $value); return $this; } public function rename_field($old, $new){ $this->_update_init('$rename'); $this->updates['$rename'][] = array($old => $new); return $this; } } class Cimongo_cursor extends Cimongo_base { protected $_cursor; public function __construct(MongoCursor $cursor){ $this->_cursor = $cursor; } public function result($as_object=TRUE){ $result = array(); try { foreach ($this->_cursor as $doc){ $result[]=$as_object?$this->_array_to_object($doc):$doc; } }catch (Exception $exception){ return $this->_handle_exception($exception->getMessage(),$as_object); } return $result; } public function has_error(){ try { $this->_cursor->next(); }catch (Exception $exception){ return $this->_handle_exception($exception->getMessage(),$as_object); } return FALSE; } public function result_array(){ return $this->result(FALSE); } public function result_object(){ return $this->result(); } public function num_rows(){ return $this->count(TRUE); } public function row($index=0, $class=NULL, $as_object=TRUE){ $size = $this->_cursor->count(); $this->_cursor->reset(); $res = array(); for($i=0;$i<$size;$i++){ $this->_cursor->next(); if($i==$index && $index<=$size){ $res = $as_object?(object)$this->_cursor->current():$this->_cursor->current(); break; } } return $res; } public function row_array($index=0, $class=NULL){ return $this->row($index, NULL, FALSE); } public function skip($x = FALSE){ if ($x !== FALSE && is_numeric($x) && $x >= 1){ return $this->_cursor->skip((int)$x); } return $this->_cursor; } public function limit($x = FALSE){ if ($x !== FALSE && is_numeric($x) && $x >= 1) { return $this->_cursor->limit((int)$x); } return $this->_cursor; } public function sort($fields) { return $this->_cursor->sort($fields); } public function count($foundOnly = FALSE) { $count = array(); try { $count = $this->_cursor->count($foundOnly); }catch (MongoCursorException $exception){ show_error($exception->getMessage(), 500); }catch (MongoConnectionException $exception){ show_error($exception->getMessage(), 500); } catch (MongoCursorTimeoutException $exception){ show_error($exception->getMessage(), 500); } return $count; } private function _array_to_object($array) { if(!is_array($array)) { return $array; } $object = new stdClass(); if (is_array($array) && count($array) > 0) { foreach ($array as $name=>$value) { $name = strtolower(trim($name)); if (!empty($name)) { $object->$name = $value; } } return $object; } else { return FALSE; } } } class Cimongo_base { protected $CI; protected $connection; protected $db; private $connection_string; private $host; private $port; private $user; private $pass; private $dbname; protected $query_safety; protected $selects = array(); protected $wheres = array(); protected $sorts = array(); protected $updates = array(); protected $limit = FALSE; protected $offset = FALSE; public function __construct(){ if (!class_exists('Mongo')){ show_error("The MongoDB PECL extension has not been installed or enabled", 500); } $this->connection_string(); $this->connect(); } public function switch_db($database = ''){ if (empty($database)){ show_error("To switch MongoDB databases, a new database name must be specified", 500); } $this->dbname = $database; try{ $this->db = $this->connection->{$this->dbname}; return (TRUE); }catch (Exception $e){ show_error("Unable to switch Mongo Databases: {$e->getMessage()}", 500); } } public function drop_db($database = ''){ if (empty($database)){ show_error('Failed to drop MongoDB database because name is empty', 500); }else{ try{ $this->connection->{$database}->drop(); return TRUE; }catch (Exception $e){ show_error("Unable to drop Mongo database `{$database}`: {$e->getMessage()}", 500); } } } public function drop_collection($db = "", $col = ""){ if (empty($db)){ show_error('Failed to drop MongoDB collection because database name is empty', 500); } if (empty($col)){ show_error('Failed to drop MongoDB collection because collection name is empty', 500); }else{ try{ $this->connection->{$db}->{$col}->drop(); return TRUE; }catch (Exception $e) { show_error("Unable to drop Mongo collection '$col': {$e->getMessage()}", 500); } } return $this; } private function connect(){ $options = array(); try{ $this->connection = new MongoClient($this->connection_string, $options); $this->db = $this->connection->{$this->dbname}; return $this; }catch (MongoConnectionException $e){ show_error("Unable to connect to MongoDB: {$e->getMessage()}", 500); } } public function connection_string(){ //global $host,$port,$user,$pass,$dbname,$query_safety,$dbhostflag; $this->host = $GLOBALS['host']; $this->port = $GLOBALS['port']; $this->user = $GLOBALS['user']; $this->pass = $GLOBALS['pass']; $this->dbname = $GLOBALS['dbname']; $this->query_safety = $GLOBALS['query_safety']; $dbhostflag = (bool)$GLOBALS['dbhostflag']; $connection_string = "mongodb://"; if (empty($this->host)){ show_error("The Host must be set to connect to MongoDB", 500); } if (empty($this->dbname)){ show_error("The Database must be set to connect to MongoDB", 500); } 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}"; } if ($dbhostflag === TRUE){ //$this->connection_string = trim($connection_string) . '/' . $this->dbname; $this->connection_string = trim($connection_string); }else{ $this->connection_string = trim($connection_string); } } protected function _clear() { $this->selects = array(); $this->updates = array(); $this->wheres = array(); $this->limit = FALSE; $this->offset = FALSE; $this->sorts = array(); } protected function _where_init($param){ if (!isset($this->wheres[$param])){ $this->wheres[$param] = array(); } } protected function _update_init($method){ if ( ! isset($this->updates[$method])){ $this->updates[$method] = array(); } } protected function _handle_exception($message,$as_object=TRUE){ if($as_object){ $res = new stdClass(); $res->has_error=TRUE; $res->error_message=$message; }else{ $res = array( "has_error"=>TRUE, "error_message"=>$message ); } return $res; } }
单独文件调用:
<?php define('BASEPATH',true); include "Cimongo.php"; $db=new Cimongo(); //count $count=$db->where(array('username'=>'ttt1'))->count_all_results('user'); //select $query=$db->or_where('username','ttt1')->or_where('username','ttt2')->limit(15,0)->order_by('username','asc')->order_by('password','asc')->get('user')->result_array(); //like //$query=$db->like('username','t')->like('password','5')->limit(15,0)->order_by('username','asc')->order_by('password','asc')->get('user')->result_array(); //where array format //$query=$db->where(array('username'=>'aaaa1'))->where(array('password'=>'dddda'))->get('user')->result_array(); //insert $data=array( 'username'=>'aaaa', 'password'=>'dddd' ); $db->insert('user',$data); $id=$data['_id']; echo $db->insert_id(); //insert end //******************** delete ****// //$db->where('username','fff')->where('password','dddd')->delete('user'); //******************** update ****// /* $update_array=array( 'username'=>"ttt" ); $query=$db->where('username','fff')->where('password','dddd')->update('user',$update_array); */ //or_where $query=$db->or_where('username','ttt1')->or_where('username','ttt2')->limit(15,0)->order_by('username','asc')->order_by('password','asc')->get('user')->result_array();
基本codeigniter 框架调用 model示例
<?php class Test_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->library("cimongo/cimongo"); $this->db=$this->cimongo; } public function test(){ $query = $this->db->get('user')->result_array(); foreach($query as $k=>$v){ //echo $v['_id']."<br>"; } $data=array( 'username'=>'aaaa', 'password'=>'dddd' ); $count=$this->db->where(array('username'=>'aaaa'))->count_all_results('user'); //$query=$this->db->where(array('username'=>'aaaa1'))->where(array('password'=>'dddda'),true)->get('user')->result_array(); //$query=$this->db->where('username','ttt')->where('password','dddd')->limit(5,0)->order_by('username','desc')->get('user')->result_array(); //$query=$this->db->limit(15,0)->order_by('username','asc')->order_by('password','asc')->get('user')->result_array(); $query=$this->db->or_where('username','ttt1')->or_where('username','ttt2')->limit(15,0)->order_by('username','asc')->order_by('password','asc')->get('user')->result_array(); //$query=$this->db->like('username','t')->like('password','5')->limit(15,0)->order_by('username','asc')->order_by('password','asc')->get('user')->result_array(); //$query=$this->db->where('username','ttt1aaaaaaaaaa')->where('username','ttt2')->limit(15,0)->order_by('username','asc')->order_by('password','asc')->get('user')->result_array(); //这种会直接取第二个条件 var_dump($query); // if($query){ // echo "user_exist"; // exit; // } /* $this->db->insert('user',$data); $id=$data['_id']; echo $this->db->insert_id(); */ //******************** update ****// /* $update_array=array( 'username'=>"ttt" ); $query=$this->db->where('username','fff')->where('password','dddd')->update('user',$update_array); */ //******************** delete ****// //$this->db->where('username','fff')->where('password','dddd')->delete('user'); } } ?>
codeigniter 添加配置 文件
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); $config['host'] = "127.0.0.1"; $config['port'] = 27017; $config['db'] = "codeigniter"; $config['user'] = "user1"; $config['pass'] = "123456"; $config['query_safety'] = TRUE; $config['db_flag'] = TRUE;