PHP Mongo curl

Source: Internet
Author: User
Tags findone php mongodb

<? PHP

/***** PHP MongoDB learning notes *///*************************// ** connect to the MongoDB database ** // ***************************** // format => ("MongoDB: // username: password @ address: Port/default database specified ", parameter) $ conn = new Mongo (); // can be abbreviated as // $ conn = new Mongo (); # connect to the 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); # Server Load balancer // $ 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: bytes //******************** * *** // ** Select database and table **////********************* * *** $ db = $ Conn-> mydb; # select mydb database // $ db = $ Conn-> selectdb ("mydb"); # The second method: $ collection = $ db-> column; # select a set (select 'table') // $ collection = $ db-> selectcollection ('column '); # method 2 // $ collection = $ Conn-> mydb-> column; # simpler method // Note: 1. databases and collections do not need to be created in advance. If they do not exist, they are automatically created. // 2. note that you may accidentally create a new database (in disorder with the original database ). // ************************** // ** insert a document **////* * *********************** // Number of inserts to the set Return bool to determine whether the insert is successful. **/$ array = array ('column _ name' => 'col '. rand (100,999), 'column _ exp' => 'xiaocai '); $ result = $ collection-> insert ($ array); # insert echo "New Record ID :". $ array ['_ id']; # MongoDB returns a record identifier var_dump ($ result); # Return Value: bool (true) // ** safely inserts data into the collection, returns the insert 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 used when a large number of records are inserted. The parameter is useful) echo "New Record ID :". $ array ['_ id']; # MongoDB returns a record identifier var_dump ($ result); # Return: array (3) {["Err"] => null ["N"] => int (0) ["OK"] => float (1 )} // ** complete syntax **/# 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 securely write data. * fsync: The default value is false. Whether to force the data to be inserted to the disk. Disk * Timeout: timeout (millisecond) ** insert result: {"_ ID": objectid ("4d63552ad549a02c01000009"), "column_name": "col770", "column_exp ": "Xiaocai"} * '_ id' is the primary key field and 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/?collection.insert.php***** // ******************************* update the document **/ /// *************************** // ** modify updates **/$ 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. Similarly, $ pull $ pullall $ pop $ Inc, the usage/** result is as follows: * original data * {"_ ID": objectid ("4D" 635ba2d549a028042503 ")," column_name ":" col123 "," column_exp ":" Xiaocai "} * is replaced with * {" _ id ": objectid (" comment ″), "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 ("4d635ba2d549a028011603 ")," Column_name ":" col709 "," column_exp ":" Xiaocai "} * is replaced with * {" _ id ": objectid (" 4d635ba2d549a028011603 ″), "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 * // ** auto-accumulate **/$ where = array ('91u' => 68 4435); $ newdata = array ('column _ exp' => 'edit'); $ result = $ collection-> Update ($ where, array ('$ set' => $ newdata,' $ inc' => array ('91u' =>-5 ))); /*** update data of 91u = 684435, 91u auto-minus 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. 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 a document **/ /// **************************/** CLEAR database **/$ collection-> remove (Array ('column _ name' => 'col399 ′)); // $ collection-> remove (); # Clear the set/** Delete the specified sequence ID **/$ id = new sequence ID ("4d638ea1d549a02801000011 ″); $ collection-> remove (Array ('_ id' => (object) $ id )) ;/*** Use the following method to match {"_ ID": objectid ("4d638ea1d549a028042511 ″)}, the same is true for queries and updates * $ id = new upload ID ("4d638ea1d549a028042511"); * array ('_ id' => (object) $ id) **/ /// ***************************/** query the number of records in the document **/echo 'count: '. $ collection-> count (). "<br>"; # All echo 'count :'. $ collection-> count (Array ('type' => 'user ')). "<br>"; # You can add the condition echo 'count :'. $ collection-> count (Array ('age' => Rray ('$ GT' => 50, '$ LTE' => 74 ))). "<br>"; #74 echo 'count: 'If the value is greater than 50 :'. $ collection-> Find ()-> limit (5)-> SKIP (0)-> count (true ). "<br>"; # 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 Set **/$ cursor = $ collection-> Find () -> snapshot (); foreach ($ cursor as $ id => $ value) {echo "$ ID:"; var_dump ($ value); echo "<br> ";} /*** Note: * after we perform the find () operation and get the $ cursor, the cursor is still dynamic. * In other words, after I find (), If a qualified record is inserted to the collection, the records are also obtained by $ cursor. * if you want to keep the result set unchanged after obtaining $ cursor, do this: * $ cursor = $ collection-> Find (); * $ cursor-> snapshot (); * For details, see shard query a data record **/$ cursor = $ collection-> findone ();/*** Note: Snapshot () cannot be used after findone () is obtained (), fields () and other functions; * // ** age, the type column does not show **/$ cursor = $ collection-> Find () -> fields (Array ("Age" => false, "type" => false );/** Only display the user column **/$ cursor = $ collection-> Find ()-> fields (Array ("user" => true )); /*** an error occurs when writing like this: $ 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, the order of the parameters/** index **/$ collection-> ensureindex (Array ('age' => 1, 'type' =>-1 )); #1 indicates descending order-1 indicates ascending order $ collectio N-> ensureindex (Array ('age' => 1, 'type' =>-1), array ('background' => true )); # create indexes in the background (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) * For details, see http://www.php.net/manual/en/#collection.ensureindex.php#//#* obtain the query result **/$ cursor = $ collection-> Find (); $ array = array (); foreach ($ curso R as $ id => $ value) {$ array [] = $ value ;} // ************************** // ** Document Clustering **////* * ********************** // this is not clear... $ Conn-> close (); # Close the connection/* differences between a 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'); CR Eate 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 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 to set the structure record structure of a node equal to the given value 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, follow these steps: $ Coll-> Update (Array ('A' => 1), array ('$ unset' =>' B '),) $ push if the corresponding node is an array, attaches a new value. If no value exists, this array is created, Append a value 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 case, the record will be: array ('A' => array (0 => 'hahahaha', 1 => 'wow'), 'B' => 1) $ pushall is similar to $ push, but multiple values are appended to a node at a time. $ addtoset if no value exists in the array of this stage, set the record structure to array ('A' => array (0 = & gt; 'hahaha'), 'B' => 1 ), if you want to attach new data to node A, then: $ Coll-> Update (Array ('B' => 1 ), array ('$ addtoset' => array ('A' => 'wow'). If wow already exists in node A, no new one will be added, if not A new item -- Wow is 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 )),) delete the first element in an array phase $ Coll-> Update (Array ('B' => 1 ), array ('$ Pop => array ('A' =>-1),) $ pull if the node is an array, delete the child item 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 a: $ Coll-> Update (Array ('B' => 1 ), array ('$ pull => array ('A' => 'hahaha'), the result is: array ('A' => array (0 => 'wow'), 'B' => 1) $ pullall is similar to $ pull, you can only delete a group of qualified records. */?>

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.