This article mainly introduces the php method for operating the MongoDB class, and analyzes the MongoDB class and its operation skills based on CI, for more information about how to operate the MongoDB class in php, see the following example. Share it with you for your reference. The details are as follows:
1. MyMongo. php file:
<? Php/*** MongoDB for downloading CI * @ author sparkHuang 2011-11-03 **/class MyMongo {private $ pai_config = "pai_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 = 999 999; private $ offset = 0; public function _ construct () {if (! Class_exists ('mongo') {$ this-> log_error ("The MongoDB PECL extentiosn has not been installed or enabled. "); exit ;}$ this-> connection_string (); $ this-> connect ();} /*** Change database **/public function switch_db ($ database = '') {if (empty ($ database )) {$ this-> log_error ("To switch MongoDB databases, a new database name must be specified"); exit ;}$ this-> dbname = $ database; try {$ this-> db = $ this-> co Nnection-> {$ this-> dbname}; return true;} catch (Exception $ e) {$ this-> log_error ("Unable to switch Mongo Databases: {$ e-> getMessage ()} "); exit ;}/ *** set the select field **/public function select ($ shortds = array (), $ excludes = array () {if (! Is_array ($ regionds) {$ regionds = (array) $ regionds;} if (! Is_array ($ excludes) {$ excludes = (array) $ excludes;} if (! Empty ($ events DS) {foreach ($ events DS as $ col) {$ this-> selects [$ col] = 1 ;}} else {foreach ($ excludes as $ col) {$ this-> selects [$ col] = 0 ;}} return ($ this );} /*** where condition query judgment ** @ usage = $ this-> condition _db-> where (array ('foo' => 'bar ')) -> get ('foobar'); **/public function where ($ wheres = array () {if (! Is_array ($ wheres) {$ wheres = (array) $ wheres;} if (! Empty ($ wheres) {foreach ($ wheres as $ wh =>$ val) {$ this-> wheres [$ wh] = $ val ;}} return ($ this);}/*** where... in .. condition query judgment ** @ usage = $ this-> resource_db-> where_in ('foo', array ('bar', 'zoo ')) -> get ('foobar'); **/public function where_in ($ field = '', $ in = array () {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ in'] = $ in; return ($ this);}/*** where... not in .. condition query judgment ** @ usage = $ t His-> maid-> where_not_in ('foo', array ('bar', 'zoo')-> get ('foobar '); **/public function where_not_in ($ field = '', $ in = array () {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ NIN'] = $ in; return ($ this);}/*** where... $ field> $ x .. condition query judgment ** @ usage = $ this-> resource_db-> where_gt ('foo', 20)-> get ('foobar '); **/public function where_gt ($ field = '', $ x) {$ this-> where_init ($ field); $ th Is-> wheres [$ field] ['$ gt'] = $ x; return ($ this);}/*** where... $ field >=$ x .. condition query judgment ** @ usage = $ this-> resource_db-> where_gte ('foo', 20)-> get ('foobar '); **/public function where_gte ($ field = '', $ x) {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ gte'] = $ x; return ($ this);}/*** where... $ field <$ x .. condition query judgment ** @ usage = $ this-> resource_db-> where_lt ('foo', 20)-> get ('foobar'); **/public Function where_lt ($ field = '', $ x) {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ lt'] = $ x; return ($ this);}/*** where... $ field <= $ x .. condition query judgment ** @ usage = $ this-> resource_db-> where_lte ('foo', 20)-> get ('foobar '); **/public function where_lte ($ field = '', $ x) {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ lte'] = $ x; return ($ this);}/*** where... $ field >=$ x AND $ field <= $ y.. Condition query judgment ** @ usage = $ this-> resource_db-> where_between ('foo', 20, 30)-> get ('foobar '); **/public function where_between ($ field = '', $ x, $ y) {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ gte'] = $ x; $ this-> wheres [$ field] [' $ lte '] = $ y; return ($ this);}/*** where... $ field> $ x AND $ field <$ y .. condition query judgment ** @ usage = $ this-> resource_db-> where_between_ne ('foo', 20, 30)-> get ('foobar'); **/publi C function where_between_ne ($ field = '', $ x, $ y) {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ gt'] = $ x; $ this-> wheres [$ field] ['$ lt'] = $ y; return ($ this);}/*** where... $ field <> $ x .. condition query judgment ** @ usage = $ this-> resource_db-> where_ne ('foo', 20)-> get ('foobar '); **/public function where_ne ($ field = '', $ x) {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ ne'] = $ x; return ($ this );}/* ** Where... or .. condition query judgment ** @ usage = $ this-> resource_db-> where_or ('foo', array ('foo', 'bar ')) -> get ('foobar'); **/public function where_or ($ field = '', $ values) {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ or'] = $ values; return ($ this);}/*** where... and .. condition query judgment ** @ usage = $ this-> resource_db-> where_and (array ('foo' => 1, 'B' => 'someexample '); */public function where_and ($ elemen Ts_values = array () {foreach ($ elements_values as $ element => $ val) {$ this-> wheres [$ element] = $ val ;} return ($ this);}/*** where $ field % $ num = $ result ** @ usage = $ this-> resource_db-> where_mod ('foo', 10, 1); */public function where_mod ($ field, $ num, $ result) {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ MoD'] = array ($ num, $ result); return ($ this );} /*** where size ** Get th E documents where the size of a field is in a given $ size int ** @ usage: $ this-> resource_db-> where_size ('foo', 1) -> get ('foobar'); */public function where_size ($ field = "", $ size = "") {$ this-> where_init ($ field ); $ this-> wheres [$ field] ['$ size'] = $ size; return ($ this );} /*** like condition query (MongoRegex class implementation defined in PHP) ** @ usage: $ this-> like _db-> like ('foo', 'bar ', 'im', false, false)-> get (); */public functi On like ($ 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] = new MongoRegex ($ regex ); return ($ this);}/*** order sorting (1 => ASC,-1 => DESC) ** @ usage: $ this-> pai_db-> get_where ('foo', array ('name' => 'Tom ')-> order_by (array ("age" => 1 )); */public function order_by ($ fields = array () {foreach ($ fields as $ col => $ val) {if ($ val =-1 | $ val = false | strtolowe R ($ val) = "desc") {$ this-> sorts [$ col] =-1 ;} else {$ this-> sorts [$ col] = 1 ;}} return ($ this) ;}/ *** limit *** @ usage: $ this-> pai_db-> get_where ('foo', array ('name' => 'Tom ')-> limit (10 ); */public function limit ($ x = 999999) {if ($ x! = NULL & is_numeric ($ x) & $ x> = 1) {$ this-> limit = (int) $ x ;}return ($ this );} /*** offset ** @ usage: $ this-> pai_db-> get_where ('foo', array ('name' => 'Tom ')) -> offset (10); */public function offset ($ x = 0) {if ($ x! = NULL & is_numeric ($ x) & $ x> = 1) {$ this-> offset = (int) $ x;} return ($ this );} /*** get_where ** @ usage: $ this-> pai_db-> get_where ('foo', array ('bar' => 'Something ')); */public function get_where ($ collection = "", $ where = array (), $ limit = 999999) {return ($ this-> where ($ where) -> limit ($ limit)-> get ($ collection);}/*** get ** @ usage: $ this-> sort _db-> where (array ('name' => 'Tom ')-> get (' Foo '); */public function get ($ collection) {if (empty ($ collection) {$ this-> log_error ("In order to retreive documents from MongoDB, a collection name must be passed "); 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 ($ results as $ result) {$ retu Rns [] = $ result;} $ this-> clear (); return ($ returns);}/*** count ** @ usage: $ this-> db-> get_where ('foo', array ('name' => 'Tom ')-> count ('Foo '); */public function count ($ collection) {if (empty ($ collection) {$ this-> log_error ("In order to retreive documents from MongoDB, a collection name must be passed "); exit;} $ count = $ this-> db-> {$ collection}-> find ($ this-> wheres) -> limit (int) $ this-> limit )-> Skip (int) $ this-> offset)-> count (); $ this-> clear (); return ($ count );} /*** insert ** @ usage: $ this-> values _db-> insert ('foo', array ('name' => 'Tom ')); */public function insert ($ collection = "", $ data = array () {if (empty ($ collection )) {$ this-> log_error ("No Mongo collection selected to delete from"); exit;} if (count ($ data) = 0 |! Is_array ($ data) {$ this-> log_error ("Nothing to insert into Mongo collection or insert is not an array"); exit ;} try {$ this-> db-> {$ collection}-> insert ($ data, array ('fsync' => true )); if (isset ($ data ['_ id']) {return ($ data [' _ id']) ;}else {return (false );}} catch (export cursorexception $ e) {$ this-> log_error ("Insert of data into MongoDB failed: {$ e-> getMessage ()}"); exit ;}} /*** update: use Mo $ Set implementation of ngoDB ** @ usage: $ this-> region _db-> where (array ('name' => 'Tom ')-> update ('foo ', array ('age' => 24) */public function update ($ collection = "", $ data = array () {if (empty ($ collection )) {$ this-> log_error ("No Mongo collection selected to delete from"); exit;} if (count ($ data) = 0 |! Is_array ($ data) {$ this-> log_error ("Nothing to update in Mongo collection or update is not an array"); exit ;} try {$ this-> db-> {$ collection}-> update ($ this-> wheres, array ('$ set' => $ data ), array ('fsync' => true, 'multiple '=> false); // Note: multiple is false return (true);} catch (writable cursorexception $ e) {$ this-> log_error ("Update of data into MongoDB failed: {$ e-> getMessage ()}"); exit ;}}/*** up Date_all: use MongoDB's $ set to implement ** @ usage: $ this-> mongo_db-> where (array ('name' => 'Tom ')) -> update_all ('foo', array ('age' => 24); */public function update_all ($ collection = "", $ data = array ()) {if (empty ($ collection) {$ this-> log_error ("No Mongo collection selected to delete from"); exit;} if (count ($ data) = 0 |! Is_array ($ data) {$ this-> log_error ("Nothing to update in Mongo collection or update is not an array"); exit ;} try {$ this-> db-> {$ collection}-> update ($ this-> wheres, array ('$ set' => $ data ), array ('fsync' => true, 'multiple '=> true); // Note: multiple is true return (true);} catch (export cursorexception $ e) {$ this-> log_error ("Update of data into MongoDB failed: {$ e-> getMessage ()}"); exit ;}}/*** dele Te ** @ usage: $ this-> your _db-> where (array ('name' => 'Tom ')-> delete ('Foo '); */public function delete ($ collection = "") {if (empty ($ collection) {$ this-> log_error ("No Mongo collection selected to delete from "); exit;} try {$ this-> db-> {$ collection}-> remove ($ this-> wheres, array ('fsync' => true, 'justone '=> true); // note that justOne is true;} catch (export cursorexception $ e) {$ this-> log_error ("Delete Of data into MongoDB failed: {$ e-> getMessage ()} "); exit ;}/ *** delete_all ** @ usage: $ this-> pai_db-> where (array ('name' => 'Tom ')-> delete_all ('Foo '); */public function delete_all ($ collection = "") {if (empty ($ collection) {$ this-> log_error ("No Mongo collection selected to delete from "); exit;} try {$ this-> db-> {$ collection}-> remove ($ this-> wheres, array ('fsync' => true, 'justone '=> fal Se); // note that justOne is false;} catch (export cursorexception $ e) {$ this-> log_error ("Delete of data into MongoDB failed: {$ e-> getMessage ()} "); exit ;}/ *** add_index ** @ usage: $ this-> pai_db-> add_index ('foo ', array ('First _ name' => 'asc ', 'Last _ name' =>-1), array ('unique' => true ))); */public function add_index ($ collection, $ keys = array (), $ options = array () {if (empty ($ collection) {$ this-> l Og_error ("No Mongo collection specified to add index to"); exit;} if (empty ($ keys) |! Is_array ($ keys) {$ this-> log_error ("Index cocould not be created to MongoDB Collection because no keys were specified"); exit ;} foreach ($ keys as $ col => $ val) {if ($ val =-1 | $ val = false | strtolower ($ val) = 'desc') {$ keys [$ col] =-1;} else {$ keys [$ col] = 1 ;}} // the validity of the $ options array is not verified here if (true = $ this-> db-> {$ collection}-> ensureIndex ($ keys, $ options )) {$ this-> clear (); return ($ this );} Else {$ this-> log_error ("An error occured when trying to add an index to MongoDB Collection"); exit ;}/ *** remove_index *** @ usage: $ this-> remove_index ('foo', array ('First _ name' => 'asc ', 'Last _ name' =>-1 )) */public function remove_index ($ collection = "", $ keys = array () {if (empty ($ collection )) {$ this-> log_error ("No Mongo collection specified to add index to"); exit;} if (Empty ($ keys) |! Is_array ($ keys) {$ this-> log_error ("Index cocould not be created to MongoDB Collection because no keys were specified"); exit ;} if ($ this-> db-> {$ collection}-> deleteIndex ($ keys) {$ this-> clear (); return ($ this );} else {$ this-> log_error ("An error occured when trying to add an index to MongoDB Collection"); exit ;}/ *** remove_all_index *** @ usage: $ this-> remove_all_index ('foo', array ('First _ name' => 'asc ', 'Last _ name' =>-1) */public function remove_all_index ($ collection = "", $ keys = array () {if (empty ($ collection) {$ this-> log_error ("No Mongo collection specified to add index to"); exit ;} if (empty ($ keys) |! Is_array ($ keys) {$ this-> log_error ("Index cocould not be created to MongoDB Collection because no keys were specified"); exit ;} if ($ this-> db-> {$ collection}-> deleteIndexes ($ keys) {$ this-> clear (); return ($ this );} else {$ this-> log_error ("An error occured when trying to add an index to MongoDB Collection"); exit ;}/ *** list_indexes ** @ usage: $ this-> pai_db-> list_indexes ('Foo'); */public Function list_indexes ($ collection = "") {if (empty ($ collection) {$ this-> log_error ("No Mongo collection specified to add index to"); exit ;} return ($ this-> db-> {$ collection}-> getIndexInfo ();}/*** drop_collection ** @ usage: $ this-> pai_db-> drop_collection ('Foo'); */public function drop_collection ($ collection = "") {if (empty ($ collection )) {$ this-> log_error ("No Mongo collection specified To add index to "); exit;} $ this-> db-> {$ collection}-> drop (); return (true );} /*** generate the MongoDB parameter string **/private function connection_string () {include_once ($ this-> pai_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 ("The Host must be set to connect to MongoDB"); exit ;} if (empty ($ this-> dbname) {$ this-> log_error ("The Database must be set to connect to MongoDB"); 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 );} /*** connect to MongoDB to obtain the database operation handle **/private function connect () {$ 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 = new Mongo ($ this-> connection_string, $ options ); $ this-> db = $ this-> connection-> {$ this-> dbname}; return ($ this);} catch (except connectionexception $ e) {$ this-> log_error ("Unable to connect to MongoDB: {$ e-> getMessage ()}");}} /*** initialize and clear some member variables **/private function clear () {$ this-> selects = array (); $ this-> wheres = array (); $ this -> Limit = NULL; $ this-> offset = NULL; $ this-> sorts = array ();} /*** initialize the $ wheres array based on the field name **/private function where_init ($ param) {if (! Isset ($ this-> wheres [$ param]) {$ this-> wheres [$ param] = array ();}} /*** error record **/private function log_error ($ msg) {$ msg = "[Date :". date ("Y-m-I H: I: s "). "]". $ msg; @ file_put_contents (". /error. log ", print_r ($ msg. "\ n", true), FILE_APPEND) ;}/ * End of MyMongo. php */
2. pai_config.php configuration file:
<?php$config["host"] = "localhost";$config["user"] = "";$config["pass"] = "";$config["port"] = 27017;$config["dbname"] = "test";$config['persist'] = TRUE;$config['persist_key'] = 'ci_mongo_persist';/*End of mongo_config.php*/
3. my‑demo. php file:
Signature <? Phpinclude_once ("MyMongo. php "); $ conn = new MyMongo (); // delete all records $ conn-> delete_all (" blog "); // Insert the first record $ value = array ("name" => "Xiaoming", "age" => 25, "addr" => array ("country" => "China", "province" => "Guangxi", "city" => "Guilin ")); $ conn-> insert ("blog", $ value); var_dump ($ conn-> select (array ("name", "age ")) -> get ("blog"); var_dump ($ conn-> get ("blog");/* End of myworkshop demo. php */
I hope this article will help you with php programming.