PHP connection to MongoDB example

Source: Internet
Author: User
Tags mongodb example
& Lt ;? Php // use the default port 27017 to connect to the local machine. of course, you can also connect to a remote host such as 192.168.0.4: 27017. if the port is 27017, the port can be omitted $ m = newMongo (); // select the comedy Database. if the database is not created before, it will be automatically created. you can also use $ m -... "> <LINKhref =" http: // www.

 

 

 

 

PHP connection to MongoDB example:

// Use the default port 27017 to connect to the local machine. of course, you can also connect to a remote host such as 192.168.0.4: 27017. if the port is 27017, the port can be omitted.

$ M = new Mongo ();

// Select the comedy Database. if the database is not created before, you can also use $ m-> selectDB ("comedy ");

$ Db = $ m-> comedy;

// Select the collection set in comedy, which is equivalent to the table in RDBMS. you can also use

$ Collection = $ db-> collection;

$ Db-> selectCollection ("collection ");

// Add an element

$ Obj = array ("title" => "Calvin and Hobbes-". date ('I: s'), "author" => "Bill Watterson ");

// Add $ obj to the $ collection

$ Collection-> insert ($ obj );

// Add another element

$ Obj = array ("title" => "XKCD-". date ('I: s'), "online" => true );

$ Collection-> insert ($ obj );

// Query all records

$ Cursor = $ collection-> find ();

// Traverse all documents in the set

Foreach ($ cursor as $ obj)

{

Echo $ obj ["title"]. "\ n ";

}

// Delete all data

$ Collection-> remove ();

// Delete hm as the name

$ Collection-> remove (array ('name' => 'hm '));

// Disconnect MongoDB

$ M-> close ();

?>

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.