Mongodb-PHP应用程序连接

时间:2014-04-21 11:56:06

标签: php mongodb

为了将Mongodb与PHP应用程序连接,我在Windows中安装了Mongodb驱动程序并启用了扩展(在phpinfo()中检查)。然后我执行以下php代码

<?php  
      // Config  
       $dbhost = 'localhost';  
       $dbname = 'test';  

      // Connect to test database  
      $m = new Mongo("mongodb://$dbhost");  
      $db = $m->$dbname;  

     // select the collection  
     $collection = $db->shows;  

     // pull a cursor query  
     $cursor = $collection->find();  
     foreach($cursor as $document) {  
     var_dump($document);  
     }   

     ?> 

并返回致命错误。怎么解决这个问题?

Fatal error: Uncaught exception 'MongoConnectionException' with message 'Failed to connect to: localhost:27017: No connection could be made because the target machine actively refused it. ' in C:\xampp\htdocs\check\index.php:7 Stack trace: #0 C:\xampp\htdocs\check\index.php(7): MongoClient->__construct('mongodb://local...') #1 {main} thrown in C:\xampp\htdocs\check\index.php on line 7

2 个答案:

答案 0 :(得分:0)

这是连接和测试wode。检查它是否在您的系统中工作:

<?php
$m = new MongoClient("localhost");
$dbname = $m->selectDB("Test");
$collection = $dbname->selectCollection("Shows"); 

$data1 = array(
        'user_id' => 'abc',
        'age' => 20,
        'Status' => 'A'
        );

$dbname = $collection->insert($data1, array('$data1' => 1));  


$results = $collection->find();

echo "<pre>";
foreach($results as $test) {
    print_r($test);
} 
echo "</pre>";

?>

答案 1 :(得分:0)

你有没有启动mongod服务器,我只能在我关闭mongod服务器时复制你的错误。