PHP Operations MongoDB

Source: Internet
Author: User
Tags findone mongodb rand


PHP Operations MongoDB


<? php
/ **
* PHP operation MongoDB study notes
* /
// *************************
// ** Connect to MongoDB database ** //
// *************************
// Format => ("mongodb: // username: password @ address: port / default specified database", parameter)
$ conn = new Mongo ();
// Can be abbreviated as
// $ conn = new Mongo (); #Connect to local host, default port.
// $ conn = new Mongo (“172.21.15.69 ″); #Connect to a remote host
// $ conn = new Mongo (“xiaocai.loc: 10086 ″); #Connect to the specified port remote host
// $ conn = new Mongo (“xiaocai.loc”, array (“replicaSet” => true)); #load balancing
// $ conn = new Mongo (“xiaocai.loc”, array (“persist” => ”t”)); #persistent connection
// $ conn = new Mongo (“mongodb: // sa: 123 @ localhost”); #With username and password
// $ conn = new Mongo (“mongodb: // localhost: 27017, localhost: 27018 ″); #Connect to multiple servers
// $ conn = new Mongo ("mongodb: ///tmp/mongo-27017.sock"); #domain socket
// $ conn = new Mongo (“mongodb: // admin_miss: miss @ localhost: 27017 / test”, array (‘persist’ => ’p ',” replicaSet ”=> true)); #complete
// Details: http://www.php.net/manual/en/mongo.connecting.php
// *************************
// ** Select database and table ** //
// *************************
$ db = $ conn-> mydb; #select mydb database
// $ db = $ conn-> selectDB (“mydb”); #Second way of writing
$ collection = $ db-> column; #select collection (select ‘table’)
// $ collection = $ db-> selectCollection (‘column’); #Second way of writing
// $ collection = $ conn-> mydb-> column; #More concise writing
// Note: 1. Databases and collections do not need to be created in advance, they will be created automatically if they do not exist.
// 2. Pay attention to typos, you may inadvertently create a new database (confusion with the original database).
// *************************
// ** Insert document ** //
// *************************
// ** Insert data into the collection and return bool to determine whether the insertion was 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 will return a record ID
var_dump ($ result); #Return: bool (true)
// ** Safely insert data into the collection and return the inserted state (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 in order to determine whether it is successful. (This parameter is more useful when there are a large number of records inserted)
echo "New record ID:". $ array ['_ id']; #MongoDB will return a record ID
var_dump ($ result); #Return: array (3) {["err"] => NULL ["n"] => int (0) ["ok"] => float (1)}
// ** Complete wording ** /
#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: default false, whether it is safe to write
* fsync: default false, whether to force insert to sync to disk
* timeout: timeout time (ms)
*
* Insertion result: {"_id": ObjectId ("4d63552ad549a02c01000009"), "column_name": "col770", "column_exp": "xiaocai"}
* ’_Id’ is the primary key field, which is added automatically by MongoDB when inserting.
*
* 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 (MongoCursorException $ e) {
* echo "Ca n’t save the same person twice! \ n";
*}
*
* Details: http://www.php.net/manual/zh/mongocollection.insert.php
* *
* /
// *************************
// ** Update document ** //
// *************************
// ** Modify and update ** /
$ where = array (‘column_name’ => ’col123 ′);
$ newdata = array (‘column_exp’ => ’GGGGGGG’, 'column_fid ’=> 444);
$ result = $ collection-> update ($ where, array ('$ set' => $ newdata)); # $ set: make a node equal to a given value, similar to $ pull $ pullAll $ pop $ inc, Slowly explain the usage in the back
/ *
* Results:
* raw data
* {"_Id": ObjectId ("4d635ba2d549a02801000003"), "column_name": "col123", "column_exp": "xiaocai"}
* Was replaced with
* {"_Id": ObjectId ("4d635ba2d549a02801000003"), "column_name": "col123", "column_exp": "GGGGGGG", "column_fid": 444}
* /
// ** Replacement update ** /
$ where = array (‘column_name’ => ’col709 ′);
$ newdata = array (‘column_exp’ => ’HHHHHHHHH’, 'column_fid ’=> 123);
$ result = $ collection-> update ($ where, $ newdata);
/ *
* Results:
* raw data
* {"_Id": ObjectId ("4d635ba2d549a02801000003"), "column_name": "col709", "column_exp": "xiaocai"}
* Was replaced with
* {“_Id”: ObjectId (“4d635ba2d549a02801000003 ″),” 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’ have been modified
* /
// ** Automatic accumulation ** /
$ where = array (’91u’ => 684435);
$ newdata = array (‘column_exp’ => ’edit’);
$ result = $ collection-> update ($ where, array (‘$ set’ => $ newdata, ’$ inc’ => array (’91u’ =>-5)));
/ **
* Update 91u = 684435 data, and 91u decrement 5
* /
/ ** delete node ** /
$ where = array (‘column_name’ => ’col685 ′);
$ result = $ collection-> update ($ where, array (‘$ unset’ => ’column_exp’));
/ **
* Delete node column_exp
* /
/ *
* *
* Complete format: update (array $ criteria, array $ newobj [, array $ options = array ()])
* Note: 1. Pay attention to distinguish between replacement update and modification update
* 2. Pay attention to distinguish data types such as array (’91u’ => ’684435’) and array (’91u’ => 684435)
* Details: http://www.mongodb.org/display/DOCS/Updating#Updating-%24bit
* *
* /
// *************************
// ** delete document ** //
// *************************
/ ** Empty database ** /
$ collection-> remove (array (‘column_name’ => ’col399 ′));
// $ collection-> remove (); #Clear collection
/ ** Delete the specified MongoId ** /
$ id = new MongoId (“4d638ea1d549a02801000011 ″);
$ collection-> remove (array (‘_ id’ => (object) $ id));
/ *
* *
* Use the following method to match {“_id”: ObjectId (“4d638ea1d549a02801000011 ″)}, query and update are the same
* $ id = new MongoId (“4d638ea1d549a02801000011 ″);
* array (‘_ id’ => (object) $ id)
* *
* /
// *************************
// ** Query documentation ** //
// *************************
/ ** Query the number of records in the document ** /
echo ‘count:’. $ collection-> count (). ”<br>”; #ALL
echo ‘count:’. $ collection-> count (array (‘type’ => ’user’)). ”<br>”; #Can add conditions
echo 'count:'. $ collection-> count (array ('age' => array ('$ gt' => 50, '$ lte' => 74))). "<br>"; # Greater than 50 Less than Equal to 74
echo ‘count:’. $ collection-> find ()-> limit (5)-> skip (0)-> count (true). ”<br>”; #Get the actual number of results returned
/ **
* Note: $ gt is greater than, $ gte is greater than or equal, $ lt is less than, $ lte is less than or equal, $ ne is not equal, $ exists does not exist
* /
/ ** All documents in the collection ** /
$ cursor = $ collection-> find ()-> snapshot ();
foreach ($ cursor as $ id => $ value) {
echo “$ id:“; var_dump ($ value); echo “<br>”;
}
/ **
* Note:
* After we did the find () operation and got the $ cursor cursor, the cursor is still dynamic.
* In other words, after my find (), until the time when my cursor loop is completed, if any eligible records are inserted into the collection, these records will also be obtained by $ cursor.
* If you want the result set after getting $ cursor unchanged, you need to do this:
* $ cursor = $ collection-> find ();
* $ cursor-> snapshot ();
* See http://www.bumao.com/index.php/2010/08/mongo_php_cursor.html for details
* /
/ ** Query a piece of data ** /
$ cursor = $ collection-> findOne ();
/ **
* Note: You cannot use snapshot (), fields () and other functions after findingOne () to get the result set;
* /
/ ** Age, type columns are not displayed ** /
$ cursor = $ collection-> find ()-> fields (array (“age” => false, ”type” => false));
/ ** Only display the user column ** /
$ cursor = $ collection-> find ()-> fields (array (“user” => true));
/ **
* If I write like this, I get an error: $ 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);
/ ** Page to get the result set ** /
$ cursor = $ collection-> find ()-> limit (5)-> skip (0);
/ ** Sort ** /
$ cursor = $ collection-> find ()-> sort (array (‘age’ =>-1, ’type’ => 1)); ## 1 means descending order -1 means ascending order, the order of the parameters affects the sort order
/ ** Index ** /
$ collection-> ensureIndex (array (‘age’ => 1, ’type’ =>-1)); # 1 means descending order -1 means ascending order
$ collection-> ensureIndex (array (‘age’ => 1, ’type’ =>-1), array (‘background’ => true)); #Index creation is run in the background (the default is to run synchronously)
$ collection-> ensureIndex (array (‘age’ => 1, ’type’ =>-1), array (‘unique’ => true)); #The 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 ** //
// *************************
// I don't understand this thing ...
$ conn-> close (); #Close the connection
/ *
The difference between relational database 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‘ Column 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, let the node value equal to N
Let the structure record structure be array (’a’ => 1, ’b’ => ’t’), if you want to add 5 to a, then:
$ coll-> update (
array (’b’ => ’t’),
array (’$ inc’ => array (’a’ => 5)),
)
$ set
Make a node equal to a given value
Let the structure record structure be array (’a’ => 1, ’b’ => ’t’), b is f plus, then:
$ coll-> update (
array (’a’ => 1),
array (’$ set’ => array (’b’ => ’f’)),
)
$ unset
Delete a node
If the record structure is array (’a’ => 1, ’b’ => ’t’), if you want to delete node b, then:
$ coll-> update (
array (’a’ => 1),
array (’$ unset’ => ’b’),
)
$ push
If the corresponding node is an array, append a new value; if it does not exist, create the array and append a value to the array; if the node is not an array, return an error.
Let the record structure be array (’a’ => array (0 => ’haha’), ’b’ = & gt; 1), if you want to append new data to node a, then:
$ coll-> update (
array (’b’ => 1),
array (’$ push’ => array (’a’ => ’wow’)),
)
In this way, the record becomes: array (’a’ => array (0 => ’haha’, 1 => ’wow’), ’b’ => 1)
$ pushAll
Similar to $ push, only multiple values are appended to a node
$ addToSet
If there is no value in the array at this stage, add it
Let the record structure be array (’a’ => array (0 = & gt; ’haha’), ’b’ => 1), if you want to append new data to the node a, then:
$ coll-> update (
array (’b’ => 1),
array (’$ addToSet’ => array (’a’ => ’wow’)),
)
If there is already a wow in the a node, then no new ones will be added, if not, a new item—wow will be added for the node.
$ pop
Let this record be array (’a’ => array (0 => ’haha’, 1 = & gt; ’wow’), ’b’ => 1)
Delete the last element of an array node:
$ coll-> update (
array (’b’ => 1),
array (’$ pop => array (’ a ’=> 1)),
)
Delete the first element of an array stage
$ coll-> update (
array (’b’ => 1),
array (’$ pop => array (’ a ’=>-1)),
)
$ pull
If the node is an array, then delete the child whose value is value, if it is not an array, an error will be returned.
Let this record be array (’a’ => array (0 => ’haha’, 1 => ’wow’), ’b’ => 1), and want to delete the sub item whose value is haha in a:
$ coll-> update (
array (’b’ => 1),
array (’$ pull => array (’ a ’=>’ haha ’)),
)
The result is: array (’a’ => array (0 => ’wow’), ’b’ => 1)
$ pullAll
Similar to $ pull, except that you can delete a set of eligible records.
* /
?>
<? php
/ **
* PHP operation MongoDB study notes
* /
// *************************
// ** Connect to MongoDB database ** //
// *************************
// Format => ("mongodb: // username: password @ address: port / default specified database", parameter)
$ conn = new Mongo ();
// Can be abbreviated as
// $ conn = new Mongo (); #Connect to local host, default port.
// $ conn = new Mongo (“172.21.15.69 ″); #Connect to a remote host
// $ conn = new Mongo (“xiaocai.loc: 10086 ″); #Connect to the specified port remote host
// $ conn = new Mongo (“xiaocai.loc”, array (“replicaSet” => true)); #load balancing
// $ conn = new Mongo (“xiaocai.loc”, array (“persist” => ”t”)); #persistent connection
// $ conn = new Mongo (“mongodb: // sa: 123 @ localhost”); #With username and password
// $ conn = new Mongo (“mongodb: // localhost: 27017, localhost: 27018 ″); #Connect to multiple servers
// $ conn = new Mongo ("mongodb: ///tmp/mongo-27017.sock"); #domain socket
// $ conn = new Mongo (“mongodb: // admin_miss: miss @ localhost: 27017 / test”, array (‘persist’ => ’p ',” replicaSet ”=> true)); #complete
// Details: http://www.php.net/manual/en/mongo.connecting.php
// *************************
// ** Select database and table ** //
// *************************
$ db = $ conn-> mydb; #select mydb database
// $ db = $ conn-> selectDB (“mydb”); #Second way of writing
$ collection = $ db-> column; #select collection (select ‘table’)
// $ collection = $ db-> selectCollection (‘column’); #Second way of writing
// $ collection = $ conn-> mydb-> column; #More concise writing
// Note: 1. Databases and collections do not need to be created in advance, they will be created automatically if they do not exist.
// 2. Pay attention to typos, you may inadvertently create a new database (confusion with the original database).
// *************************
// ** Insert document ** //
// *************************
// ** Insert data into the collection and return bool to determine whether the insertion was 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 will return a record ID
var_dump ($ result); #Return: bool (true)
// ** Safely insert data into the collection and return the inserted state (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 in order to determine whether it is successful. (This parameter is more useful when there are a large number of records inserted)
echo "New record ID:". $ array ['_ id']; #MongoDB will return a record ID
var_dump ($ result); #Return: array (3) {["err"] => NULL ["n"] => int (0) ["ok"] => float (1)}
// ** Complete wording ** /
#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: default false, whether it is safe to write
* fsync: default false, whether to force insert to sync to disk
* timeout: timeout time (ms)
*
* Insertion result: {"_id": ObjectId ("4d63552ad549a02c01000009"), "column_name": "col770", "column_exp": "xiaocai"}
* ’_Id’ is the primary key field, which is added automatically by MongoDB when inserting.
*
* 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 (MongoCursorException $ e) {
* echo "Ca n’t save the same person twice! \ n";
*}
*
* Details: http://www.php.net/manual/zh/mongocollection.insert.php
* *
* /
// *************************
// ** Update document ** //
// *************************
// ** Modify and update ** /
$ where = array (‘column_name’ => ’col123 ′);
$ newdata = array (‘column_exp’ => ’GGGGGGG’, 'column_fid ’=> 444);
$ result = $ collection-> update ($ where, array ('$ set' => $ newdata)); # $ set: make a node equal to a given value, similar to $ pull $ pullAll $ pop $ inc, Slowly explain the usage in the back
/ *
* Results:
* raw data
* {"_Id": ObjectId ("4d635ba2d549a02801000003"), "column_name": "col123", "column_exp": "xiaocai"}
* Was replaced with
* {"_Id": ObjectId ("4d635ba2d549a02801000003"), "column_name": "col123", "column_exp": "GGGGGGG", "column_fid": 444}
* /
// ** Replacement update ** /
$ where = array (‘column_name’ => ’col709 ′);
$ newdata = array (‘column_exp’ => ’HHHHHHHHH’, 'column_fid ’=> 123);
$ result = $ collection-> update ($ where, $ newdata);
/ *
* Results:
* raw data
* {"_Id": ObjectId ("4d635ba2d549a02801000003"), "column_name": "col709", "column_exp": "xiaocai"}
* Was replaced with
* {“_Id”: ObjectId (“4d635ba2d549a02801000003 ″),” 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’ have been modified
* /
// ** Automatic accumulation ** /
$ where = array (’91u’ => 684435);
$ newdata = array (‘column_exp’ => ’edit’);
$ result = $ collection-> update ($ where, array (‘$ set’ => $ newdata, ’$ inc’ => array (’91u’ =>-5)));
/ **
* Update 91u = 684435 data, and 91u decrement 5
* /
/ ** delete node ** /
$ where = array (‘column_name’ => ’col685 ′);
$ result = $ collection-> update ($ where, array (‘$ unset’ => ’column_exp’));
/ **
* Delete node column_exp
* /
/ *
* *
* Complete format: update (array $ criteria, array $ newobj [, array $ options = array ()])
* Note: 1. Pay attention to distinguish between replacement update and modification update
* 2. Pay attention to distinguish data types such as array (’91u’ => ’684435’) and array (’91u’ => 684435)
* Details: http://www.mongodb.org/display/DOCS/Updating#Updating-%24bit
* *
* /
// *************************
// ** delete document ** //
// *************************
/ ** Empty database ** /
$ collection-> remove (array (‘column_name’ => ’col399 ′));
// $ collection-> remove (); #Clear collection
/ ** Delete the specified MongoId ** /
$ id = new MongoId (“4d638ea1d549a02801000011 ″);
$ collection-> remove (array (‘_ id’ => (object) $ id));
/ *
* *
* Use the following method to match {“_id”: ObjectId (“4d638ea1d549a02801000011 ″)}, query and update are the same
* $ id = new MongoId (“4d638ea1d549a02801000011 ″);
* array (‘_ id’ => (object) $ id)
* *
* /
// *************************
// ** Query documentation ** //
// *************************
/ ** Query the number of records in the document ** /
echo ‘count:’. $ collection-> count (). ”<br>”; #ALL
echo ‘count:’. $ collection-> count (array (‘type’ => ’user’)). ”<br>”; #Can add conditions
echo 'count:'. $ collection-> count (array ('age' => array ('$ gt' => 50, '$ lte' => 74))). "<br>"; # Greater than 50 Less than Equal to 74
echo ‘count:’. $ collection-> find ()-> limit (5)-> skip (0)-> count (true). ”<br>”; #Get the actual number of results returned
/ **
* Note: $ gt is greater than, $ gte is greater than or equal, $ lt is less than, $ lte is less than or equal, $ ne is not equal, $ exists does not exist
* /
/ ** All documents in the collection ** /
$ cursor = $ collection-> find ()-> snapshot ();
foreach ($ cursor as $ id => $ value) {
echo “$ id:“; var_dump ($ value); echo “<br>”;
}
/ **
* Note:
* After we did the find () operation and got the $ cursor cursor, the cursor is still dynamic.
* In other words, after my find (), until the time when my cursor loop is completed, if any eligible records are inserted into the collection, these records will also be obtained by $ cursor.
* If you want the result set after getting $ cursor unchanged, you need to do this:
* $ cursor = $ collection-> find ();
* $ cursor-> snapshot ();
* See http://www.bumao.com/index.php/2010/08/mongo_php_cursor.html for details
* /
/ ** Query a piece of data ** /
$ cursor = $ collection-> findOne ();
/ **
* Note: You cannot use snapshot (), fields () and other functions after findingOne () to get the result set;
* /
/ ** Age, type columns are not displayed ** /
$ cursor = $ collection-> find ()-> fields (array (“age” => false, ”type” => false));
/ ** Only display the user column ** /
$ cursor = $ collection-> find ()-> fields (array (“user” => true));
/ **
* If I write like this, I get an error: $ cursor-> fields (array (“age” => true, ”type” => false));
* /
/ ** (type, age node exists) and age! = 0 and age <50 ** /

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.