PHP Operation MongoDB Database

Source: Internet
Author: User
Tags findone

Recently, there is a project that needs to operate mongoDb data with PHP.
1, connect to MongoDB database
$ conn = new Mongo ();
Other links
// $ conn = new Mongo (); #Connect to localhost, default port.
// $ conn = new Mongo (“172.21.15.69 ″); #Connect to a remote host
// $ conn = new Mongo ("xiaocai.loc: 10086 ″); #connect to the remote host with the specified port
// $ 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 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
2, select the database and table
$ Db = $ conn-> mydb; #Select mydb database
$ Collection = $ db-> myTable; #Select collection (select 'table')
// $ collection = $ db-> selectCollection (myTable); #second writing
// $ collection = $ conn-> mydb-> myTable; #More concise writing
3, Insert data record
$ 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 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 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)}
4, update data records
// ** Modify and update Traditional 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, similarly $ pull $ pullAll $ pop $ inc, Use slowly later
/ *
* Results:
* raw data
* {"_Id": ObjectId ("4d635ba2d549a02801000003 ″)," column_name ":" col123 "," column_exp ":" xiaocai "}
* Replaced with
* {"_Id": ObjectId ("4d635ba2d549a02801000003 ″)," column_name ":" col123 "," column_exp ":" GGGGGGG "," column_fid ": 444}
* /
// ** Replace update, overwrite original record ** /
$ where = array (‘column_name’ => ’col709 ′);
$ newdata = array (‘column_exp’ => ’HHHHHHHHHH’, 'column_fid ’=> 123);
$ result = $ collection-> update ($ where, $ newdata);
/ *
* Results:
* raw data
* {"_Id": ObjectId ("4d635ba2d549a02801000003 ″)," column_name ":" col709 "," column_exp ":" xiaocai "}
* 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 ’is modified
* /
// ** Automatic accumulation ** /
$ where = array (’91u’ => 684435);
$ newdata = array (‘column_exp’ => ’edit’);
$ result = $ collection-> update ($ where, array (‘$ set’ => $ newdata, ’$ inc’ => array (’91u’ =>-5)));
/ **
* Update the data of 91u = 684435, and decrease 91u by 5
* /
PHP operation MongoDB database summary record

5, delete record operation
// ** delete node ** /
$ where = array (‘column_name’ => ’col685’);
$ result = $ collection-> update ($ where, array (‘$ unset’ => ’column_exp’));
/ **
* Delete node column_exp
* /
/ *
* *
* Full format: update (array $ criteria, array $ newobj [, array $ options = array ()])
* Note: 1. Note the distinction between replacement update and modification update
* 2. Pay attention to distinguish data types such as array (’91u’ => ’684435 ′) and array (’ 91u ’=> 684435)
* *
* /
// ** clear table ** /
$ collection-> remove (); #Empty the collection
// ** delete the specified MongoId ** /
$ id = new MongoId ("4d638ea1d549a02801000011 ″);
$ collection-> remove (array (‘_ id’ => (object) $ id));
6, query data records
// ** Statistics table records ** /
echo ‘count:’. $ collection-> count (). ”<br>”; #All
echo ‘count:’. $ collection-> count (array (‘type’ => ’user’)). ”<br>”; #Statistic ‘type’ is a record of user
echo 'count:'. $ collection-> count (array ('age' => array ('$ gt' => 50, '$ lte' => 74))). "<br>"; #Statistics greater than 50 74 or less
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 to, $ lt is less than or equal to, $ lte is less than or equal to, $ ne is not equal to, and $ exists does not exist
* /
// ** Get all records in the table ** /
$ cursor = $ collection-> find ()-> snapshot ();
foreach ($ cursor as $ id => $ value) {
echo "$ id:"; var_dump ($ value); echo "<br>";
}
/ **
* Note:
* After we did find () operation and obtained $ cursor cursor, the cursor is still dynamic.
* In other words, after I find (), until my cursor loop is completed, if there are any more eligible records inserted into the collection, these records will also be obtained by $ cursor.
* If you want the result set to remain unchanged after you get $ cursor, you need to do this:
* $ cursor = $ collection-> find ();
* /
// ** Query a piece of data ** /
$ cursor = $ collection-> findOne ();
/ **
* Note: you cannot use functions such as snapshot (), fields () after findOne () has obtained the result set;
* /
// ** Set display field age, type column is not displayed ** /
$ cursor = $ collection-> find ()-> fields (array ("age" => false, "type" => false));
$ cursor = $ collection-> find ()-> fields (array ("user" => true)); // Only display the user column
/ **
* I will make an error writing this: $ cursor-> fields (array (“age” => true, ”type” => false));
* /
// ** Set conditions (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);
// ** Get the result set by pagination ** /
$ 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, 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)); #The creation of the index 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/mongoco
llection.ensureindex.php
* /
// ** Get query results ** /
$ cursor = $ collection-> find ();
$ array = array ();
foreach ($ cursor as $ id => $ value) {
$ array [] = $ value;
}
7. Close link
$ Conn-> close (); #Close the connection
8, common function use
A. $ Inc If the recorded node exists, increase the value of the node by N; if the node does not exist, let the value of the node equal to N
Suppose the structure record structure is array (’a’ => 1, ’b’ => ’t’), and you want to increase a by 5, then:
$ Coll-> update (array (’b’ => ’t’), array (’$ inc’ => array (’a’ => 5)))
B. $ Set makes a node equal to a given value
Suppose the structure record structure is array (’a’ => 1, ’b’ => ’t’), b is plus f, then:
$ Coll-> update (array (’a’ => 1), array (’$ set’ => array (’b’ => ’f’)))
C. $ Unset delete a node
Suppose the record structure is array (’a’ => 1, ’b’ => ’t’), and you want to delete the b node, then:
$ Coll-> update (array (’a’ => 1), array (’$ unset’ => ’b’))
D. $ Push If the corresponding node is an array, append a new value; if it does not exist, create this array and append a value to this array; if the node is not an array, return an error.
Suppose the record structure is array (’a’ => array (0 => ’haha’), ’b’ = & gt; 1), and you want to append new data to node a, then:
$ Coll-> update (array (’b’ => 1), array (’$ push’ => array (’a’ => ’wow’)))
This way, the record will become: array (’a’ => array (0 => ’haha’, 1 => ’wow’), ’b’ => 1)
E. $ PushAll is similar to $ push, but it will append multiple values to a node at a time
F. $ AddToSet If there is no value in the array at this stage, add it
Suppose the record structure is 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 a wow in the a node, then no new one will be added, if not, a new item-wow will be added for the node.
G. $ Pop Let this record be array (’a’ => array (0 => ’haha’, 1 => ’wow’), ’b’ => 1)
Remove 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)))
H. $ Pull If the node is an array, delete the child whose value is value. If it is not an array, an error will be returned.
Suppose the record is array (’a’ => array (0 => ’haha’, 1 => ’wow’), ’b’ => 1), and you want to delete the child whose value is haha:
$ Coll-> update (array (’b’ => 1), array (’$ pull => array (’ a ’=>’ haha ’)))
The result is: array (’a’ => array (0 => ’wow’), ’b’ => 1)
I. $ PullAll is similar to $ pull, except that you can delete a set of eligible records.


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.