PHP connection to MongoDB sample code

Source: Internet
Author: User

Copy codeThe Code is as follows:
<? 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 = 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"]. "<br/> \ 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.