Php operations on mongodb

Source: Internet
Author: User
Tags findone php mongodb
********************************** Connect to the MongoDB database * * ************************* format ("mongodb: username: password @ address: Specifies the database by default on the port ", parameter) $ connnewMongo (); can be abbreviated as $ connnewMongo ();#

/***** 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 (); #

  

/**

* 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

// $ Conn = new Mongo (); # connect to the local host, default port.

// $ Conn = new Mongo ("172.21.15.69"); # connect to the remote host

// $ Conn = new Mongo ("xiaocai. loc: 10086"); # connect to the remote host on the specified port

// $ 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"); # password with user name

// $ 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

// 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 method **/

# 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.

*/

?>

  

/**

* 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

// $ Conn = new Mongo (); # connect to the local host, default port.

// $ Conn = new Mongo ("172.21.15.69"); # connect to the remote host

// $ Conn = new Mongo ("xiaocai. loc: 10086"); # connect to the remote host on the specified port

// $ 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"); # password with user name

// $ 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

// 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 method **/

# 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.

[1] [2]

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.