PHP connects to the MongoDB sample code

  • 2020-05-24 05:17:39
  • OfStack

 
<?php 
// The default connection is used here 27017 Of course you can also connect to remote hosts such as 192.168.0.4:27017, If the port is 27017 , the port can be omitted  
$m = new Mongo(); 
//  choose comedy A database can also be used if it was not previously created automatically $m->selectDB("comedy"); 
$db = $m->comedy; 
// choose comedy The inside of the collection Set is equal to RDBMS Inside the table, too - You can use  
$collection = $db->collection; 
$db->selectCollection("collection"); 
// add 1 An element  
$obj = array( "title" => "Calvin and Hobbes-".date('i:s'), "author" => "Bill Watterson" ); 
// will $obj  Added to the $collection  In the collection  
$collection->insert($obj); 
// Add another 1 An element  
$obj = array( "title" => "XKCD-".date('i:s'), "online" => true ); 
$collection->insert($obj); 
// Query all records  
$cursor = $collection->find(); 
// Iterate through all the documents in the collection  
foreach ($cursor as $obj) 
{ 
echo $obj["title"] . "<br />\n"; 
} 
// Delete all data  
//$collection->remove(); 
// delete  name  for hm 
//$collection->remove(array('name'=>'hm')); 
// Disconnect the MongoDB The connection  
$m->close(); 
?> 

Related articles: