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