TP already supports MongoDB database, here is a detailed description of the configuration and use of MONGO on TP.
(1) There is a bug in the original class of/think/model/mongomodel.class.php in the tp3.2.2 version. We need to add some code to the original class to fix the bug.
+----------------------------------------------------------------------namespace Think\model;use think\model;/ * * Mongomodel Model class * Implements ODM and Activerecords mode */class Mongomodel 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 object with Mongoid object 2 Int Shaping support automatically grows 3 string string hash protected $_idtype = Self::type_int; Whether the primary key is self-increment protected $_autoinc = true; MONGO default off field detection can dynamically append field protected $autoCheckFields = false; Chain Operation method List 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 method name * @param array $args call parameters * @return Mixed */Public function __call ($method, $args) {if (In_array (Strtolower ($method), $this->method S,true)) { The implementation of the coherent operation $this->options[strtolower ($method)] = $args [0]; return $this; }elseif (Strtolower (substr ($method, 0,5)) = = ' Getby ') {//Get records based on a field $field = Parse_name (substr ($me thod,5)); $where [$field] = $args [0]; return $this->where ($where)->find (); }elseif (Strtolower (substr ($method, 0,10)) = = ' Getfieldby ') {//Get a value for a record based on a field $name = Parse_name (s Ubstr ($method, 10)); $where [$name] = $args [0]; return $this->where ($where)->getfield ($args [1]); }else{E (__class__. ': '. $method. L (' _method_not_exist_ ')); Return }}/** * Get field information and cache primary key and self-increment information directly configured * @access public * @return void */Public Function flush () { The cache does not exist query data table information $fields = $this->db->getfields (); if (! $fields) {//temporarily no data cannot get field information the next query return false; } $this->fields = Array_keYs ($fields); foreach ($fields as $key = + $val) {//record field type $type [$key] = $val [' type ']; }//Record field type information if (C (' Db_fieldtype_check ')) $this->fields[' _type ') = $type; 2008-3-7 increased Cache switch control if (C (' Db_fields_cache ')) {//Permanent cache data table information $db = $this->dbname? $this-& Gt;dbname:c (' db_name '); F (' _fields/'. $db. '. $this->name, $this->fields); }}//The callback method before writing data includes new and updated protected function _before_write (& $data) {$pk = $this->getpk (); Processing primary key data according to primary key type if (Isset ($data [$PK]) && $this->_idtype = = self::type_object) {$data [$PK] = new \mongoid ($data [$PK]); }}/** * Count statistics with where coherent operation * @access public * @return Integer */Public Function count () { Parse expression $options = $this->_parseoptions (); return $this->db->count ($options); }/** * Gets the next ID for auto-grow type * @access public * @param string $pk field name default to primary KEY * @return mixed */Public function getmongonextid ($pk = ') { if (empty ($PK)) {$pk = $this->getpk (); } return $this->db->mongo_next_id ($PK); /** * Added data * @access public * @param mixed $data data * @param array $options expression * @param boolean $replace if replace * @return mixed */Public function Add ($data = ", $opti {if (empty ($data)) { Does not pass data, gets 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; }}//parse expression $options = $this->_parseoptions ($options); Data processing $data = $this->_facade ($data); if (false = = = $this->_before_insert ($data, $options)) { return false; }//write data to 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 inserting data protected function _before_insert (& $data, $options) {//write data to database if ($this->_aut Oinc && $this->_idtype== self::type_int) {//primary key auto-grow $PK = $this->getpk (); if (!isset ($data [$PK])) {$data [$pk] = $this->db->mongo_next_id ($PK); }}} Public function clear () {return $this->db->clear (); }//callback method after successful query protected function _after_select (& $resultSet, $options) {Array_walk ($resultSet, Array ($thi S, ' checkmongoid ')); }/** * Get mongoid * @access protected * @param array $result return numberAccording to * @return Array */protected function checkmongoid (& $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 \mongoid ($options [' where '] [$id]); }}/** * Query data * @access public * @param mixed $options expression parameter * @return Mixed */public func tion Find ($opti {if (is_numeric ($options) | | is_string ($options)) {$id = $this->getpk (); $where [$id] = $options; $options = Array (); $options [' where '] = $where; }//Parse expression $options = $this->_parseoptions ($options); $result = $this->db->find ($Options); if (false = = = $result) {return false; if (empty ($result)) {//query result is null return null; }else{$this->checkmongoid ($result); } $this->data = $result; $this->_after_find ($this->data, $options); return $this->data; /** * Field value grows * @access public * @param string $field field name * @param integer $step growth value * @return bo Olean */Public Function setinc ($field, $step =1) {return $this->setfield ($field, Array (' Inc ', $step)); /** * Field value decreased * @access public * @param string $field field name * @param integer $step Decrease value * @return bo Olean */Public Function Setdec ($field, $step =1) {return $this->setfield ($field, Array (' Inc ', '-'. $step)); /** * Gets a field value for a record * @access public * @param string $field 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;//reset to null return array} $resultSet = $this->db->select ($options); if (!empty ($resultSet)) {$_field = explode (', ', $field); $field = Array_keys ($resultSet [0]); $key = Array_shift ($field); $key 2 = Array_shift ($field); Resolve parameter $field The returned result $key incorrect if the field order specified is inconsistent with the order of the record fields in the database//2015-08-15 by Bing if (! ( Array_search ($_field[0], Array_keys ($resultSet [0])) (===false)) {$key =$_field[0]; $key 2=$_field[1]; } $cols = Array (); $count = count ($_field); foreach ($resultSet as $result) {$name = $result[$key]; if (2== $count) {$cols [$name] = $result [$key 2]; }else{$cols [$name] = Is_null ($SEPA)? $result: Implode ($sepa, $result); }} return $cols; }}else{//Returns the number of data if (true!== $sepa) {//Returns all data when SEPA is specified as true $options [' Lim It '] = 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; /** * Execute MONGO instruction * @access public * @param array $command instruction * @return Mixed */public functio n Command ($command) {return $this->db->command ($command); }/** * Executes Mongocode * @access public * @param string $code mongocode * @param array $args parameter * @ return mixed */Public function Mongocode ($code, $args =array ()) {return $this->db->execute ($code, $args ); }//After database switchover callback method protected function _after_db () {//Toggle collection//bing 2015-8-15 get data table if (Empty ($t His->dbname) &&!empty ($this->connection)) {$db _c $this->dbname= $db _config[' db_name ']; } $this->db->switchcollection ($this->gettablename (), $this->dbname); }/** * Get full 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 complete MONGO class after the modification.
which
(1)
protected $connection = ' Db_mongo '; is the Db_mongo (2) corresponding to the Link configuration config
Resolve parameter $field The returned result $key incorrect if the field order specified is inconsistent with the order of the record fields in the database //2015-08-15 by Bing if (! ( Array_search ($_field[0], Array_keys ($resultSet [0])) (===false)) { $key =$_field[0]; $key 2=$_field[1]; }
This piece is added to create a database cache
(3)
Bing 2015-8-15 Get datasheet if (empty ($this->dbname) &&!empty ($this->connection)) { $db _c $ This->dbname= $db _config[' db_name ']; } $this->db->switchcollection ($this->gettablename (), $this->dbname);
This function in the TP original Mongomodel will only be linked to the MySQL configuration dbname, now to make changes, as shown above.
Second, configure the Db_mongo in TP
(1) Add in config file
' Db_mongo ' =>array (' db_type ' = ' MONGO ',//database type ' db_host ' = ' localhost ',//server address ' db_name ' = > ' Test ',//database name ' Db_user ' + ',// user name ' db_pwd ' + ' ,//password ' db_port ' = ' 27017 ',//port,
MONGO is not certified by default, so the user name and password are empty.
(2) Additions to the Mongomodel
protected $connection = ' Db_mongo '; is the Db_mongo of the link configuration config, which is the complete MONGO class above.
The configuration of the database is now complete.
Third, install Php_mongo drive
Installing drivers on Windows must correspond to the large version of PHP that you use.
(1) Download the corresponding version of Php_mongo.
(2) Copy the Php_mongo.dll into the PHP ext file
(3) Add Extension=php_mongo.dll to PHP.ini
(4) Restart Apache
(5) Visit phpinfo, search MONGO
The presence above represents a successful configuration.
Iv. curd operation of MONGO on TP
(1) PHP connection MONGO, creating instantiated objects
$m =new \think\model\mongomodel (' user ');
Where "User" is a collection, which is equivalent to a table in MySQL.
(2) Add--add ()
Query is basically the same as MySQL,
Example
$data =array ( "Name" = "John Doe", "addr" and "Shenzhen", "sex" = "male", "info" =>array ( "Age" = " Phone" = "12345", ) ;
$result = $m->add ($data);
This adds the data as a document, equivalent to a record of MySQL.
(2) Inquiry--select (), GetField ()
If you want to query the $data that you just inserted,
$map [' name ']= "John Doe",
$result = $m->where ($map)->select ();
The entire document is searched, and an array is returned.
Array (5) { ["_id"] + int (4) ["name"] + = string (6) "John Doe" ["addr"] + string (6) "Shenzhen" ["sex"] = > String (3) "Male" ["info"] = + Array (2) { ["age"] + int (+) ["phone"] = + string (5) "12345" }< c8/>}
If you want to check a field, you can use GetField ();
$result = $m->where ($map)->getfield (' info ');
Find out.
Array (2) { ["age"] + int (+) ["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)
Query of Time section, to be queried in array form
For example, there is a key "time" in the document to find documents between 2015/815-2015/9/1.
$map =array (' Time ' =>array (' $gt ' =>int, ' $lt ' =>int))
$result = $m->where ($map)->select ()
where int represents the timestamp.
(3) Delete--delete ();
$result = $m->where ($map)->delete ();
The deletion of this delete is to delete the entire document.
(4) Modify--save ()
Set
For example, re-modify the sex=> ' male ' in the document and change to Sex=> ' "female"
$update [' Sex ']=array (' Set ', ' female '); $m->where ($map)->save ($update);
Results:
Array (5) { ["_id"] + int (4) ["name"] + = string (6) "John Doe" ["addr"] + string (6) "Shenzhen" ["sex"] = > String (3) "Female" ["info"] = + Array (2) { ["age"] + int (+) ["phone"] = + string (5) "12345" }
For example, modify the value of a key in an inline document, such as age
$update [' Info.age ']=array (' Set '), $m->where ($map)->save ($update);
Results:
Array (5) { ["_id"] + int (3) ["name"] + = string (6) "John Doe" ["addr"] + string (6) "Shenzhen" ["sex"] = > String (3) "Female" ["info"] = + Array (2) { ["age"] + int (+) ["phone"] = + string (5) "12345" }< c8/>}
unset
For example, to delete a key.
For example, delete the addr key in the document
$update [' addr ']=array (' unset '); $m->where ($map)->save ($update);
Results:
Array (4) { ["_id"] + int (3) ["name"] + = string (6) "John Doe" ["sex"] = + string (3) "Female" ["info"] = > Array (2) { ["age"] + int (+) ["phone"] + = string (5) "12345"} }
you can see there's no addr key.
push--append a value to the field (must be an array type) inside
such as an array (this does not include a relational array)
$data =array ( "Name" = "John Doe", "addr" and "Shenzhen", "sex" = "male", "info" =>array ( "Age" = " Phone" = "12345", " num" =>array (); ); $result = $m->add ($data);
Num is an array that modifies the added data inside.
$update [' num ']=array (' push ', 1); $m->where ($map)->save ($update);
Results:
Array (5) { ["_id"] + int (3) ["name"] + = string (6) "John Doe" ["sex"] = + string (3) "Female" ["info"] = > Array (2) { ["age"] + int (+) ["phone"] + = string (5) "12345" } ["num"] = = Array (1) { C27/>[0] = Int (1) } }
If you want to add an array
$update [' num ']=array (' push ', array (' subject ' = ' php ')); $m->where ($map)->save ($update);
Results:
Array (5) { ["_id"] + int (3) ["name"] + = string (6) "John Doe" ["sex"] + = string (3) "Female" ["info"] = Array (2) { ["age"] + int (+) ["phone"] + = string (5) "12345" } ["num"] = + Array (2) { [ 0] = = Int (1) [1] = = Array (1) { ["subject"] = + string (3) "PHP"}} }
pull--A value in the Delete field (must be an array field) by value
Now you want to delete the array (' suject ' + ' php ') that you just added in the NUM array
$update [' num ']=array (' pull ', array (' subject ' = ' php ')); $m->where ($map)->save ($update);
Results:
Array (5) { ["_id"] + int (3) ["name"] + = string (6) "John Doe" ["sex"] + = string (3) "Female" ["info"] = Array (2) { ["age"] + int (+) ["phone"] + = string (5) "12345" } ["num"] = + Array (1) { [0] =& Gt Int (1) } }
You can see that the NUM array has no Array (' suject ' = ' php ');
(5) Statistical--count ()
$result = $m->where ($map)->count ();
At this point, the above methods are tested in practice, MONGO most commonly used, can meet the business requirements of the method summary end. If there is anything wrong, please point out!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The above describes the TP on the MONGO configuration, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.