Home  >  Article  >  Backend Development  >  PHP connection to MongoDB sample code_PHP tutorial

PHP connection to MongoDB sample code_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:16:43904browse

Copy the code The code is as follows:

//The default port 27017 used to connect to this machine is used here. Of course you 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 comedy database. If the database has not been created before, it will be automatically created. You can use $m->selectDB("comedy");
$db = $m->comedy;
//Select the collection in comedy, which is equivalent to the table in RDBMS, and can also be used
$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
$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 records in the collection Document
foreach ($cursor as $obj)
{
echo $obj["title"] . "
n";
}
//Delete all data
//$collection->remove();
//Remove name as hm
//$collection->remove(array('name'=>'hm'));
//Disconnect MongoDB
$m->close();
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325839.htmlTechArticleCopy the code code as follows: ?php //The default connection port 27017 of this machine is used here. Of course, you can also connect The remote host is such as 192.168.0.4:27017. If the port is 27017, the port can be omitted...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn