: This article mainly introduces the PHP MongoDB learning notes. if you are interested in the PHP Tutorial, you can refer to them.
/**
* PHP MongoDB learning Notes
*/
//*************************
// ** Connect to the MongoDB database **//
//*************************
// Format => ("mongodb: // user name: password @ Address: Port/default database", parameter)
$ Conn = new Mongo ();
// Can be abbreviated
// $ C Mongo (); # connect to the local host, default port.
// $ C Mongo ("172.21.15.69"); # connect to the remote host
// $ C Mongo ("xiaocai. loc: 10086"); # connect to the remote host on the specified port
// $ C Mongo ("xiaocai. loc", array ("replicaSet" => true); # server load balancer
// $ C Mongo ("xiaocai. loc", array ("persist" => "t"); # persistent connection
// $ C Mongo ("mongodb: // sa: 123 @ localhost"); # Password with user name
// $ C Mongo ("mongodb: // localhost: 27017, localhost: 27018"); # connect to multiple servers
// $ C Mongo ("mongodb: // tmp/mongo-27017.sock"); # domain socket
// $ C Mongo ("mongodb: // admin_miss: miss @ localhost: 27017/test", array ('persist '=> 'P ', "replicaSet" => true); # Complete
// Detailed information: http://www.php.net/manual/en/mongo.connecting.php
//*************************
// ** Select database and table **//
//*************************
$ Db = $ conn-> mydb; # select mydb database
// $ Db = $ conn-> selectDB ("mydb"); # Method 2
$ Collection = $ db-> column; # select a set (select 'table ')
// $ Collection = $ db-> selectCollection ('column'); # Method 2
// $ Collection = $ conn-> mydb-> column; # simpler writing method
// Note: 1. databases and collections do not need to be created in advance. if they do not exist, they will be created automatically.
// 2. pay attention to the typos. you may accidentally create a new database (chaotic with the original database ).
//*************************
// ** Insert document **//
//*************************
// ** Insert data into the collection and return bool to determine whether the insertion is successful .**/
$ Array = array ('column _ name' => 'col'. rand (100,999), 'column _ exp' => 'xiaocai ');
$ Result = $ collection-> insert ($ array); # Simple insert
Echo "New Record ID:". $ array ['_ id']; # MongoDB returns a record id
Var_dump ($ result); # Return value: bool (true)
// ** Safely insert data into the collection and return the insertion status (array ).**/
$ Array = array ('column _ name' => 'col'. rand (100,999), 'column _ exp' => 'xiaocai2 ′);
$ Result = $ collection-> insert ($ array, true); # Used to Wait for MongoDB to complete the operation to determine whether the operation is successful. (This parameter is useful when a large number of records are inserted)
Echo "New Record ID:". $ array ['_ id']; # MongoDB returns a record id
Var_dump ($ result); # Return: array (3) {["err"] => NULL ["n"] => int (0) ["OK"] => float (1 )}
Complete Writing
Insert ($ array, array ('Safe '=> false, 'fsync' => false, 'timeout' => 10000 ))
/*
**
* Complete format: insert (array $ a [, array $ options = array ()])
* Insert (array (), array ('Safe '=> false, 'fsync' => false, 'timeout' => 10000 ))
* Parameter: safe: The default value is false. whether to write data securely.
* Fsync: The default value is false. whether to force the data to be inserted to the disk.
* Timeout: timeout (MS)
*
* Insert result: {"_ id": ObjectId ("4d63552ad549a02c01000009"), "column_name": "col770", "column_exp": "xiaocai "}
* '_ Id' is the primary key field, which is automatically added when MongoDB is inserted.
*
* Note: 1. the following two inserts are the same record (same _ id) because they have the same value.
* $ Collection-> insert (array ('column _ name' => 'xiaocai '));
* $ Collection-> insert (array ('column _ name' => 'xiaocai '));
* Avoid
* $ Collection-> insert (array ('column _ name' => 'xiaocai '), true );
* Try {
* $ Collection-> insert (array ('column _ name' => 'xiaocai '), true );
*} Catch (except cursorexception $ e ){
* Echo "Can't save the same person twice! \ N ";
*}
*
* Details: http://www.php.net/manual/zh/mongocollection.insert.php
**
*/
//*************************
// ** UPDATE document **//
//*************************
// ** Modify update **/
$ Where = array ('column _ name' => 'col123 ′);
$ Newdata = array ('column _ exp '=> 'gggggggggg', 'column _ fid' => 444 );
$ Result = $ collection-> update ($ where, array ('$ set' => $ newdata); # $ set: equals a node to a given value, for example, $ pull $ pullAll $ pop $ inc.
/*
* Result:
* Original data
* {"_ Id": ObjectId ("4d635ba2d549a028036903"), "column_name": "col123", "column_exp": "xiaocai "}
* Replaced
* {"_ Id": ObjectId ("4d635ba2d549a028036903"), "column_name": "col123", "column_exp": "GGGGGGG", "column_fid": 444}
*/
// ** Replace UPDATE **/
$ Where = array ('column _ name' => 'col709 ′);
$ Newdata = array ('column _ exp' => 'hhhhhhh ', 'column _ fid' => 123 );
$ Result = $ collection-> update ($ where, $ newdata );
/*
* Result:
* Original data
* {"_ Id": ObjectId ("4d635ba2d549a028036903"), "column_name": "col709", "column_exp": "xiaocai "}
* Replaced
* {"_ Id": ObjectId ("4d635ba2d549a028036903"), "column_exp": "HHHHHHHHH", "column_fid": 123}
*/
// ** Batch update **/
$ Where = array ('column _ name' => 'col ');
$ Newdata = array ('column _ exp' => 'multiple ', '91u' => 684435 );
$ Result = $ collection-> update ($ where, array ('$ set' => $ newdata), array ('multiple' => true ));
/**
* All 'column _ name' = 'col' are modified.
*/
// ** Automatically accumulate **/
$ Where = array ('91u' = & gt; 684435 );
$ Newdata = array ('column _ exp' => 'Edit ');
$ Result = $ collection-> update ($ where, array ('$ set' => $ newdata, '$ Inc' => array ('91u' =>-5 )));
/**
* Update data of 91u = 684435, and 91u is automatically reduced by 5.
*/
/** Delete a node **/
$ Where = array ('column _ name' => 'col685 ′);
$ Result = $ collection-> update ($ where, array ('$ unset' => 'column _ exp '));
/**
* Delete a node column_exp
*/
/*
**
* Complete format: update (array $ criteria, array $ newobj [, array $ options = array ()])
* Note: 1. Note the difference between replacement update and modification update.
* 2. differentiate data types such as array ('91u' => '000000') and array ('91u' => 684435)
* Details: http://www.mongodb.org/display/DOCS/Updating#Updating-%24bit
**
*/
//*************************
// ** Delete document **//
//*************************
/** Clear the database **/
$ Collection-> remove (array ('column _ name' => 'col399 ′));
// $ Collection-> remove (); # clear the collection
/** Delete the specified consumer ID **/
$ Id = new consumer id ("4d638ea1d549a028038511 ″);
$ Collection-> remove (array ('_ id' => (object) $ id ));
/*
**
* Use the following method to match {"_ id": ObjectId ("4d638ea1d549a028042511")}. the query and update operations are the same.
* $ Id = new consumer id ("4d638ea1d549a028038511 ″);
* Array ('_ id' => (object) $ id)
**
*/
//*************************
// ** Query document **//
//*************************
/** Query the number of records in a document **/
Echo 'Count: '. $ collection-> count ()."
"; # All
Echo 'Count: '. $ collection-> count (array ('type' => 'user '))."
"; # Conditions can be added.
Echo 'Count :'. $ collection-> count (array ('age' => array ('$ gt' => 50, '$ lte' => 74 )))."
"; # Greater than 50, less than or equal to 74
Echo 'Count: '. $ collection-> find ()-> limit (5)-> skip (0)-> count (true )."
"; # Obtain the actual number of returned results
/**
* Note: $ gt is greater than, $ gte is greater than or equal to, $ lt is less than, $ lte is less than or equal to, $ ne is not equal to, and $ exists does not exist.
*/
/** All documents in the collection **/
$ Cursor = $ collection-> find ()-> snapshot ();
Foreach ($ cursor as $ id => $ value ){
Echo "$ id:"; var_dump ($ value); echo"
";
}
/**
* Note:
* After we perform the find () operation and obtain the $ cursor, the cursor is still dynamic.
* In other words, after I find (), after the completion of my cursor loop, if any more qualified records are inserted into the collection, these records will also be obtained by $ cursor.
* If you want to keep the result set unchanged after obtaining $ cursor, you need to do the following:
* $ Cursor = $ collection-> find ();
* $ Cursor-> snapshot ();
* See http://www.bumao.com/index.php/2010/08/mongo_php_cursor.html
*/
/** Query a piece of data **/
$ Cursor = $ collection-> findOne ();
/**
* Note: functions such as snapshot () and fields () cannot be used after findOne () obtains the result set;
*/
/** Age, the type column is not displayed **/
$ Cursor = $ collection-> find ()-> fields (array ("age" => false, "type" => false ));
/** Show only the user column **/
$ Cursor = $ collection-> find ()-> fields (array ("user" => true ));
/**
* In this case, an error occurs: $ cursor-> fields (array ("age" => true, "type" => false ));
*/
/** (Type, age node exists) and age! = 0 and age <50 **/
$ Where = array ('type' => array ('$ exists' => true), 'age' => array (' $ ne '=> 0, '$ lt' => 50, '$ exists' => true ));
$ Cursor = $ collection-> find ($ where );
/** Retrieve result sets by page **/
$ Cursor = $ collection-> find ()-> limit (5)-> skip (0 );
/** Sort **/
$ Cursor = $ collection-> find ()-> sort (array ('age' =>-1, 'type' => 1 )); #1 indicates descending order-1 indicates ascending order, and the order of parameters is affected
/** Index **/
$ Collection-> ensureIndex (array ('age' => 1, 'type' =>-1); #1 indicates descending order-1 indicates ascending order
$ Collection-> ensureIndex (array ('age' => 1, 'type' =>-1), array ('background' => true )); # create indexes in the background for running (synchronous operation by default)
$ Collection-> ensureIndex (array ('age' => 1, 'type' =>-1), array ('unique' => true )); # This index is unique.
/**
* EnsureIndex (array (), array ('name' => 'index name', 'background' = true, 'Unique' = true ))
* See: http://www.php.net/manual/en/mongocollection.ensureindex.php
*/
/** Get query results **/
$ Cursor = $ collection-> find ();
$ Array = array ();
Foreach ($ cursor as $ id => $ value ){
$ Array [] = $ value;
}
//*************************
// ** Document clustering **//
//*************************
// This is not clear...
$ Conn-> close (); # close the connection
/*
Differences between RDS and MongoDB data storage
MySql data structure:
CREATE TABLE IF NOT EXISTS
Column
(
Column_id
Int (16) not null auto_increment COMMENT 'primary key ',
Column_name
Varchar (32) not null comment 'topic name ',
Primary key (
Column_id
)
);
CREATE TABLE IF NOT EXISTS
Article
(
Article_id
Int (16) not null auto_increment COMMENT 'primary key ',
Article_caption
Varchar (15) not null comment 'title ',
Primary key (
Article_id
)
);
CREATE TABLE IF NOT EXISTS
Article_body
(
Article_id
int(16) NOT NULL COMMENT ‘article.article_id’,
Body
Text COMMENT 'body'
);
MongoDB data structure:
$ Data = array (
'Column _ name' => 'default ',
'Article' => array (
'Article _ caption '=> 'xiaocai ',
'Body' => 'xxxxxxxxxx... '
)
);
$ Inc
If the recorded node exists, Add N to the value of the node. if the node does not exist, Add N to the value of the node.
Set the structure record to array ('a' => 1, 'B' => 'T'). If you want ATO add 5, then:
$ Coll-> update (
Array ('B' => 'T '),
Array ('$ Inc' => array ('a' => 5 )),
)
$ Set
Make a node equal to the given value
Set the structure record to array ('a' => 1, 'B' => 'T'), and B to add f, then:
$ Coll-> update (
Array ('a' => 1 ),
Array ('$ set' => array (' B '=> 'F ')),
)
$ Unset
Delete a node
Set the Record structure to array ('a' => 1, 'B' => 'T'). to delete node B, then:
$ Coll-> update (
Array ('a' => 1 ),
Array ('$ unset' =>' B '),
)
$ Push
If the corresponding node is an array, a new value is appended; if the node does not exist, the array is created and a value is appended to the array. if the node is not an array, an error is returned.
Set the Record structure to array ('a' => array (0 => 'hahaha'), 'B' = & gt; 1), and add new data to node, so:
$ Coll-> update (
Array ('B' => 1 ),
Array ('$ push' => array ('a' => 'wow ')),
)
In this way, the record will become: array ('a' => array (0 => 'hahahaha', 1 => 'wow'), 'B' => 1)
$ PushAll
Similar to $ push, only multiple values are appended to a node at a time.
$ AddToSet
If no value exists in the array of this stage, add
Set the Record structure to array ('a' => array (0 = & gt; 'hahaha'), 'B' => 1 ), to attach new data to node:
$ Coll-> update (
Array ('B' => 1 ),
Array ('$ addtoset' => array ('a' => 'wow ')),
)
If wow already exists in node a, no new item will be added. if not, a new item -- wow will be added to the node.
$ Pop
Set this record to array ('a' => array (0 => 'hahaha', 1 = & gt; 'wow'), 'B' => 1)
Delete the last element of an array node:
$ Coll-> update (
Array ('B' => 1 ),
Array ('$ pop => array ('a' => 1 )),
)
Deletes the first element of an array.
$ Coll-> update (
Array ('B' => 1 ),
Array ('$ pop => array ('a' =>-1 )),
)
$ Pull
If the node is an array, delete the subitem whose value is value. if it is not an array, an error is returned.
Set this record to array ('a' => array (0 => 'hahaha', 1 => 'wow'), 'B' => 1 ), to delete the sub-item whose value is haha in:
$ Coll-> update (
Array ('B' => 1 ),
Array ('$ pull => array ('a' => 'hahaha ')),
)
Result: array ('a' => array (0 => 'wow'), 'B' => 1)
$ PullAll
Like $ pull, you can only delete a set of qualified records.
*/
?>
'). AddClass ('pre-numbering '). hide (); $ (this ). addClass ('Has-numbering '). parent (). append ($ numbering); for (I = 1; I <= lines; I ++) {$ numbering. append ($ ('
'). Text (I) ;}; $ numbering. fadeIn (1700) ;}) ;}; script
The above introduces the learning notes for PHP operations on MongoDB, including some content. I hope my friends who are interested in the PHP Tutorial will be helpful.