部署一个快速的云服务器,只是为了托管一个MongoDB,出于好奇而修补它。它已安装并正常运行。做了这样的测试DB /表:
db.items.insert({ name: 'eggs', quantity: 10, price: 1.50 })
db.items.insert({ name: 'bacon', quantity: 3, price: 3.50 })
db.items.insert({ name: 'tomatoes', quantity: 30, price: 0.50 })
当我运行db.items.find({})
时,所有项目都显示出来并且一切正常。
现在在PHP中,当我从另一台服务器连接到该数据库时,我这样做:
// open connection to MongoDB server
$conn = new Mongo('mongodb://theAdmin:Gold1234@165.225.130.252:27017');
// access database
$db = $conn->test;
// access collection
$collection = $db->items;
// execute query
// retrieve all documents
$cursor = $collection->find();
// iterate through the result set
// print each document
echo $cursor->count() . ' document(s) found. <br/>';
foreach ($cursor as $obj) {
echo 'Name: ' . $obj['name'] . '<br/>';
echo 'Quantity: ' . $obj['quantity'] . '<br/>';
echo 'Price: ' . $obj['price'] . '<br/>';
echo '<br/>';
}
我收到此错误:
致命错误:未捕获异常'MongoConnectionException' 消息'无法连接到:165.225.130.252:27017:传输 在/home/moosex/public_html/info.php:4中没有连接端点 堆栈跟踪:#0 /home/moosex/public_html/info.php(4): Mongo-&gt; __ construct('mongodb:// [theA ...')#1 {main}抛出 第4行/home/moosex/public_html/info.php
我抬起头来尝试了几种不同的连接方法,但仍然无法获得它。我该如何远程连接?
BTW,这是该服务器的实际用户名密码和地址(除了鸡蛋培根和西红柿之外没有任何东西),如果你可以连接它,上帝保佑你大声笑。答案 0 :(得分:1)
为了能够像这样调试“随机怪异”,打开内部驱动程序日志记录非常有用。 驱动程序在幕后完成了很多工作,并且可以吐出各种重要的调试信息。
在脚本顶部添加以下内容:
<?php
MongoLog::setLevel(MongoLog::ALL);
MongoLog::setModule(MongoLog::ALL);
?>
默认情况下,记录器将显示“php错误消息”(E_NOTICE / E_WARNING),如果启用了error_log,请确保检查该文件以获得结果。
对于您的(略微修改过的)连接字符串,我得到以下结果
Notice: PARSE INFO: Parsing mongodb://theAdmin:Gold1234@localhost:27027 in Command line code on line 1
Notice: PARSE INFO: - Found user 'theAdmin' and a password in Command line code on line 1
Notice: PARSE INFO: - Found node: localhost:27027 in Command line code on line 1
Notice: PARSE INFO: - Connection type: STANDALONE in Command line code on line 1
Notice: PARSE INFO: - No database name found for an authenticated connection. Using 'admin' as default database in Command line code on line 1
Notice: CON INFO: mongo_get_read_write_connection: finding a STANDALONE connection in Command line code on line 1
Notice: CON INFO: connection_create: creating new connection for localhost:27027 in Command line code on line 1
Notice: CON WARN: connection_create: error while creating connection for localhost:27027: Invalid argument in Command line code on line 1
Notice: CON WARN: Couldn't connect to 'localhost:27027': Invalid argument in Command line code on line 1
我怀疑两端都有防火墙问题。你能用mongo shell连接到服务器吗?