: This article mainly introduces the configuration of mongo on tp. if you are interested in the PHP Tutorial, refer to it. Tp already supports mongodb databases. The following describes how to configure and use mongo on tp.
(1) the original class of/think/Model. class. php in tp3.2.2 has bugs. We need to add some code to the original class to fix the bug.
// + ------------------------------------------------------------------------ Namespace Think \ Model; use Think \ Model; /***** modeling class * implements the ODM and ActiveRecords modes */class modeling Model extends Model {// primary key type const TYPE_OBJECT = 1; const TYPE_INT = 2; const TYPE_STRING = 3; // primary key name protected $ pk = '_ id'; // _ id type 1 the Object adopts the struct id Object 2 Int integer and supports automatic growth of 3 String Hash protected $ _ idType = self:: TYPE_INT; // master Whether the key is auto-incrementing protected $ _ autoinc = true; // Mongo disables field detection by default and can dynamically append the field protected $ autoCheckFields = false; // list of chain operation methods protected $ methods = array ('table', 'order', 'auto', 'filter', 'validate '); // database configuration protected $ connection = 'DB _ MONGO '; /*** use the _ call method to implement some special Model Methods * @ access public * @ param string $ method name * @ param array $ args call parameter * @ return mixed * /public function _ call ($ method, $ args) {if (in_array (str Tolower ($ method), $ this-> methods, true) {// coherent operation implementation $ this-> options [strtolower ($ method)] = $ args [0]; return $ this;} elseif (strtolower (substr ($ method, 0, 5) = 'getby ') {// Obtain the record $ field = parse_name (substr ($ method, 5) based on a field; $ where [$ field] = $ args [0]; return $ this-> where ($ where)-> find ();} elseif (strtolower (substr ($ method,) = 'getfieldby ') {// Obtain a record value based on a field $ name = parse_name (substr ($ method, 10); $ Where [$ name] = $ args [0]; return $ this-> where ($ where)-> getField ($ args [1]);} else {E (_ CLASS __. ':'. $ method. L ('_ METHOD_NOT_EXIST _'); return ;}} /*** get the field information and cache the primary key and auto-increment information. directly configure * @ access public * @ return void */public function flush () {// if the cache does not exist, query the data table information $ fields = $ this-> db-> getFields (); if (! $ Fields) {// if no data exists, you cannot obtain the field information. return false next time.} $ this-> fields = array_keys ($ fields ); foreach ($ fields as $ key => $ val) {// record field type $ type [$ key] = $ val ['type'];} // record the field type information if (C ('Db _ FIELDTYPE_CHECK ') $ this-> fields [' _ type'] = $ type; //-7 add cache switch control if (C ('Db _ FIELDS_CACHE ') {// permanently cache data table information $ DB = $ this-> dbName? $ This-> dbName: C ('Db _ name'); F ('_ fields /'. $ db. '. '. $ this-> name, $ this-> fields) ;}// the callback method before data writing includes adding and updating protected function _ before_write (& $ data) {$ pk = $ this-> getPk (); // process the primary key data if (isset ($ data [$ pk]) based on the primary key type. & $ this-> _ idType = self: TYPE_OBJECT) {$ data [$ pk] = new \ Upload ID ($ data [$ pk]);} /*** count statistics combined with where coherent operations ** @ access public * @ return integer */public function count () {// analysis expression $ options = $ t His-> _ parseOptions (); return $ this-> db-> count ($ options );} /*** get the next ID for automatic growth * @ access public * @ param string $ pk field name is the primary key by default * @ return mixed */public function getMongoNextId ($ pk ='') {if (empty ($ pk) {$ pk = $ this-> getPk ();} return $ this-> db-> pai_next_id ($ pk );} /*** add data ** @ access public * @ param mixed $ data * @ param array $ options expression * @ param boolean $ replace whether to replace * @ return mixed * /Public function add ($ data = '', $ opti {if (empty ($ data) {// no data is transferred, get the value of the current data object if (! Empty ($ this-> data) {$ data = $ this-> data; // reset data $ this-> data = array ();} else {$ this-> error = L ('_ DATA_TYPE_INVALID _'); return false ;}// analysis expression $ options = $ this-> _ parseOptions ($ options ); // data processing $ data = $ this-> _ facade ($ data); if (false ===$ this-> _ before_insert ($ data, $ options )) {return false;} // write data to the database $ result = $ this-> db-> insert ($ data, $ options, $ replace); if (false! ==$ Result) {$ this-> _ after_insert ($ data, $ options); if (isset ($ data [$ this-> getPk ()]) {return $ data [$ this-> getPk ()] ;}return $ result ;}// callback method before data insertion protected function _ before_insert (& $ data, $ options) {// write data to the database if ($ this-> _ autoinc & $ this-> _ idType = self: TYPE_INT) {// automatic primary key growth $ pk = $ this-> getPk (); if (! Isset ($ data [$ pk]) {$ data [$ pk] = $ this-> db-> pai_next_id ($ pk) ;}} public function clear () {return $ this-> db-> clear ();} // The callback method protected function _ after_select (& $ resultSet, $ options) {array_walk ($ resultSet, array ($ this, 'checkupid '));} /*** obtain the upload ID * @ access protected * @ param array $ result returned data * @ return array */protected function checkted ID (& $ result) {if (is_object ($ result ['_ id ']) {$ Result [' _ id'] = $ result ['_ id']->__ toString ();} return $ result ;} // expression filter callback method protected function _ options_filter (& $ options) {$ id = $ this-> getPk (); if (isset ($ options ['where'] [$ id]) & is_scalar ($ options ['where'] [$ id]) & $ this-> _ idType = self: TYPE_OBJECT) {$ options ['where'] [$ id] = new \ consumer id ($ options ['where'] [$ id]);} /*** query data ** @ access public * @ param mixed $ options expression parameter * @ retu Rn mixed */public function find ($ opti {if (is_numeric ($ options) | is_string ($ options) {$ id = $ this-> getPk (); $ where [$ id] = $ options; $ options = array (); $ options ['where'] = $ where ;} // analysis expression $ options = $ this-> _ parseOptions ($ options); $ result = $ this-> db-> find ($ options ); if (false ===$ result) {return false;} if (empty ($ result) {// The query result is empty return null ;} else {$ this-> checkaskid ($ result);} $ This-> data = $ result; $ this-> _ after_find ($ this-> data, $ options); return $ this-> data ;} /*** field value growth * @ access public * @ param string $ field name * @ param integer $ step growth value * @ return boolean */public function setInc ($ field, $ step = 1) {return $ this-> setField ($ field, array ('INC', $ step ));} /*** decrease field value * @ access public * @ param string $ field name * @ param integer $ step decrease value * @ return boolean */public funct Ion setDec ($ field, $ step = 1) {return $ this-> setField ($ field, array ('INC ','-'. $ step ));} /*** obtain a field value of a record * @ access public * @ param string $ field name * @ param string $ spea field data interval symbol * @ return mixed */public function getField ($ field, $ sepa = null) {$ options ['field'] = $ field; $ options = $ this-> _ parseOptions ($ options); if (strpos ($ field ,', ') {// multi-field if (is_numeric ($ sepa) {// limited quantity $ options ['limit'] = $ Sepa; $ sepa = null; // The Returned array is reset to null} $ resultSet = $ this-> db-> select ($ options); if (! Empty ($ resultSet) {$ _ field = explode (',', $ field); $ field = array_keys ($ resultSet [0]); $ key = array_shift ($ field); $ key2 = array_shift ($ field ); // solve the problem that the returned result $ key is incorrect when the field sequence specified by the parameter $ field is inconsistent with the field sequence recorded in the database. // by bing if (! (Array_search ($ _ field [0], array_keys ($ resultSet [0]) === false) {$ key = $ _ field [0]; $ key2 = $ _ field [1] ;}$ cols = array (); $ count = count ($ _ field); foreach ($ resultSet as $ result) {$ name = $ result [$ key]; if (2 = $ count) {$ cols [$ name] = $ result [$ key2];} else {$ cols [$ name] = is_null ($ sepa )? $ Result: implode ($ sepa, $ result) ;}}return $ cols ;}} else {// number of returned data if (true! ==$ Sepa) {// When sepa is set to true, all data is returned. $ options ['limit'] = is_numeric ($ sepa )? $ Sepa: 1;} // find a record $ result = $ this-> db-> select ($ options); if (! Empty ($ result) {foreach ($ result as $ val) {if (strpos ($ field ,'. ') {$ tmp = explode ('. ', $ field); foreach ($ tmp as $ t) {$ val = $ val [$ t];} $ array [] = $ val ;} else {$ array [] = $ val [$ field] ;}} return 1 ==$ options ['limit']? $ Array [0]: $ array;} return null ;} /*** run the Mongo command * @ access public * @ param array $ command * @ return mixed */public function command ($ command) {return $ this-> db-> command ($ command );} /*** run the response code * @ access public * @ param string $ code response code * @ param array $ args parameter * @ return mixed */public function response code ($ code, $ args = array () {return $ this-> db-> execute ($ code, $ args);} // Database Callback method after switching protected function _ after_db () {// switch Collection // bing get the data table if (empty ($ this-> dbName )&&! Empty ($ this-> connection) {$ db_c $ this-> dbName = $ db_config ['DB _ name'];} $ this-> db-> switchCollection ($ this-> getTableName (), $ this-> dbName );} /*** get the complete data table name Mongo table name without dbName * @ access public * @ return string */public function getTableName () {if (empty ($ this-> trueTableName) {$ tableName =! Empty ($ this-> tablePrefix )? $ This-> tablePrefix: ''; if (! Empty ($ this-> tableName) {$ tableName. = $ this-> tableName;} else {$ tableName. = parse_name ($ this-> name);} $ this-> trueTableName = strtolower ($ tableName);} return $ this-> trueTableName ;}}
The above is a modified complete mongo class.
Where
(1)
Protected $ connection = 'DB _ MONGO '; it is the DB_mongo (2) corresponding to the link configuration config)
// Solve the problem that the returned result $ key is incorrect when the field sequence specified by the parameter $ field is inconsistent with the field sequence recorded in the database. // by bing if (! (Array_search ($ _ field [0], array_keys ($ resultSet [0]) === false) {$ key = $ _ field [0]; $ key2 = $ _ field [1];}
This is added to create the database cache.
(3)
// Obtain the data table if (empty ($ this-> dbName )&&! Empty ($ this-> connection) {$ db_c $ this-> dbName = $ db_config ['DB _ name'];} $ this-> db-> switchCollection ($ this-> getTableName (), $ this-> dbName );This function is only linked to the configuration dbname of MYSQL by default in the original tp model, and is to be modified, as shown above.
2. configure DB_MONGO in tp
(1) add
'Db _ MONGO '=> array ('Db _ type' => 'Mongo', // Database TYPE 'DB _ host' => 'localhost ', // server address 'DB _ name' => 'test', // database NAME 'DB _ user' => '', // username 'DB _ pwd' => '', // password 'DB _ port' => '123', // PORT ),Mongo is not authenticated by default, so the username and password are empty.
(2) add an external model
Protected $ connection = 'DB _ MONGO '; is the DB_mongo class corresponding to the link configuration config, which is the complete Mongo class above.
So far, the database configuration has been completed.
3. install the php_mongo driver
To install a driver on Windows, you must match your own php version.
(1) Download the corresponding version of php_mongo.
(2) copy php_cmd.dll to the ext file of php.
(3) add extension = php_assist.dll to php. ini.
(4) restart Apache
(5) access phpinfo and search for mongo
The preceding figure indicates that the configuration is successful.
IV. CURD operations of mongo on tp
(1) php connects to mongo and creates an instantiated object
$m=new \Think\Model\MongoModel('user');"User" is a set, which is equivalent to a table in mysql.
(2) add -- add ()
Query is basically the same as mysql,
Example:
$ Data = array ("name" => "", "addr" => "Shenzhen", "sex" => "male ", "info" => array ("age" => 20, "phone" => "12345 ",),);$ Result = $ m-> add ($ data );
In this way, the data is added as a document, which is equivalent to a record of mysql.
(2) query -- select (), getField ()
To query the inserted $ data
$ Map ['name'] = "Li Si ",
$result=$m->where($map)->select();
The entire document is searched and an array is returned.
Array (5) {["_ id"] => int (4) ["name"] => string (6) "Li Si" ["addr"] => string (6) "Shenzhen" ["sex"] => string (3) "male" ["info"] => array (2) {["age"] => int (20) ["phone"] => string (5) "12345 "}}
If you want to query a field, you can use getField ();
$result=$m->where($map)->getField('info');Detected
array(2) { ["age"] => int(20) ["phone"] => string(5) "12345"}If you want to check the value of the age key, directly
$result=$m->where($map)->getField('info.age');Returns int (20)
Time segment query, which must be in the form of an array
For example, if there is a key "time" in the document, you need to find the document between 2015/815-2015/9/1.
$map=array('time'=>array('$gt'=>int,'$lt'=>int))
$result=$m->where($map)->select()
Int indicates the timestamp.
(3) delete -- delete ();
$result=$m->where($map)->delete();
The delete operation deletes the entire document.
(4) modify -- save ()
Set
For example, modify the sex => 'male' in the document and change it to sex => '"female"
$ Update ['sex'] = array ('set', 'female '); $ m-> where ($ map)-> save ($ update );Result:
Array (5) {["_ id"] => int (4) ["name"] => string (6) "Li Si" ["addr"] => string (6) "Shenzhen" ["sex"] => string (3) "Female" ["info"] => array (2) {["age"] => int (20) ["phone"] => string (5) "12345 "}For example, modify the value of a key in the embedded document, such as age
$update['info.age']=array('set',30);$m->where($map)->save($update);
Result:
Array (5) {["_ id"] => int (3) ["name"] => string (6) "Li Si" ["addr"] => string (6) "Shenzhen" ["sex"] => string (3) "Female" ["info"] => array (2) {["age"] => int (30) ["phone"] => string (5) "12345 "}}
Unset
For example, you want to delete a key.
For example, deleting the addr key in the document
$update['addr']=array('unset'); $m->where($map)->save($update);
Result:
Array (4) {["_ id"] => int (3) ["name"] => string (6) "Li Si" ["sex"] => string (3) "female" ["info"] => array (2) {["age"] => int (30) ["phone"] => string (5) "12345 "}}
We can see that no addr key is available.
Push -- append a value to the field (which must be of the array type)
For example, an array (relational array not included here)
$ Data = array ("name" => "", "addr" => "Shenzhen", "sex" => "male ", "info" => array ("age" => 20, "phone" => "12345",), "num" => array ();); $ result = $ m-> add ($ data );Num is an array that modifies and adds data to it.
$update['num']=array('push',1);$m->where($map)->save($update);Result:
Array (5) {["_ id"] => int (3) ["name"] => string (6) "Li Si" ["sex"] => string (3) "female" ["info"] => array (2) {["age"] => int (30) ["phone"] => string (5) "12345"} ["num"] => array (1) {[0] => int (1 )}}If you want to add an array
$update['num']=array('push',array('subject'=>'php')); $m->where($map)->save($update);
Result:
Array (5) {["_ id"] => int (3) ["name"] => string (6) "Li Si" ["sex"] => string (3) "female" ["info"] => array (2) {["age"] => int (30) ["phone"] => string (5) "12345"} ["num"] => array (2) {[0] => int (1) [1] => array (1) {["subject"] => string (3) "php "}}}
Pull -- delete a value in a field (which must be an array field) based on the value
Now you need to delete the array ('suobject' => 'php') added to the num array ')
$update['num']=array('pull',array('subject'=>'php')); $m->where($map)->save($update);Result:
Array (5) {["_ id"] => int (3) ["name"] => string (6) "Li Si" ["sex"] => string (3) "female" ["info"] => array (2) {["age"] => int (30) ["phone"] => string (5) "12345"} ["num"] => array (1) {[0] => int (1 )}}
We can see that there is no array in the num array ('suobject' => 'php ');
(5) statistics -- count ()
$ Result = $ m-> where ($ map)-> count ();
So far, the above methods have been tested in practice. mongo is the most common method that can meet business requirements. If anything is wrong, please point it out!
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.
The above introduces the configuration of mongo on tp, including some content, and hope to be helpful to friends who are interested in PHP tutorials.