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 ();
?>